Attaching click to anchor tag in angular

前端 未结 13 1615
臣服心动
臣服心动 2020-12-13 12:02

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 ?



        
相关标签:
13条回答
  • 2020-12-13 12:40

    I think you are not letting Angular work for you.

    In angular 2:

    1. Remove the href tag from <a> to prevent a page forwarding.
    2. Then just add your usual Angular click attribute and function.
    3. Add to style: "cursor: pointer" to make it act like a button
    0 讨论(0)
  • 2020-12-13 12:43

    You 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>
    
    0 讨论(0)
  • 2020-12-13 12:44

    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:

    html

    <a href="" (click)="openChangePasswordForm()">Change expired password</a>
    

    ts

    openChangePasswordForm(): boolean {
      console.log("openChangePasswordForm called!");
      return false;
    }
    
    0 讨论(0)
  • 2020-12-13 12:50

    <a href="javascript:void(0);" (click)="onGoToPage2()">Go to Page 2</a>

    0 讨论(0)
  • 2020-12-13 12:53

    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

    0 讨论(0)
  • 2020-12-13 12:57
    <a href="#" (click)="onGoToPage2()">Go to page 2</a>
    
    0 讨论(0)
提交回复
热议问题