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 ?
I think you are not letting Angular work for you.
In angular 2:
href
tag from <a>
to prevent a page forwarding.style: "cursor: pointer"
to make it act like a buttonYou can use routerLink (which is an alternative of href
for angular 2+) with click event as below to prevent from page reloading
<a [routerLink]="" (click)="onGoToPage2()">Go to page</a>
I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false
in order to prevent the page being refreshed:
<a href="" (click)="openChangePasswordForm()">Change expired password</a>
openChangePasswordForm(): boolean {
console.log("openChangePasswordForm called!");
return false;
}
<a href="javascript:void(0);" (click)="onGoToPage2()">Go to Page 2</a>
I had issues with the page reloading but was able to avoid that with routerlink="."
:
<a routerLink="." (click)="myFunction()">My Function</a>
I received inspiration from the Angular Material docs on buttons: https://material.angular.io/components/button/examples
<a href="#" (click)="onGoToPage2()">Go to page 2</a>