I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?
You can try something like this:
<a href="javascript: void(0);" (click)="method()">
OR
<a href="javascript: void(0);" [routerLink]="['/abc']">
You just need to add !!
before your click method handler call: (click)="!!onGoToPage2()"
. The !!
will prevent the default action from happening by converting the return of your method to a boolean. If it's a void
method, then this will become false
.
I've been able to get this to work by simply using [routerLink]="[]"
. The square brackets inside the quotes is important. No need to prevent default actions in the method or anything. This seems to be similar to the "!!" method but without needing to add that unclear syntax to the start of your method.
So your full anchor tag would look like this:
<a [routerLink]="[]" (click)="clickMethod()">Your Link</a>
Just make sure your method works correctly or else you might end up refreshing the page instead and it gets very confusing on what is actually wrong!
You can use routerLink
which is an alternative of href
for angular 2.**
Use routerLink
as below in html
<a routerLink="/dashboard">My Link</a>
and make sure you register your routerLink
in modules.ts or router.ts like this
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent }
]
I had to combine several of the answers to get a working solution.
This solution will:
Not navigate to http://mySite/#
<a href="#" (click)="!!functionToCall()">Link</a>
I was able to implement this successfully
<a [routerLink]="['/login']">abc</a>