Attaching click to anchor tag in angular

前端 未结 13 1617
臣服心动
臣服心动 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 13:06

    I have examined all the above answer's, We just need to implement two things to work it as expected.

    Step - 1: Add the (click) event in the anchor tag in the HTML page and remove the href=" " as its not supported in the Angular, Instead use routerLink = " "

    <ul>
      <li><a routerLink="" (click)="hitAnchor1($event)"><p>Click One</p></a></li>
      <li><a routerLink="" (click)="hitAnchor2($event)"><p>Click Two</p></a></li>
    </ul>
    

    Step - 2: Call the above function to attach the click event to anchor tags (coming from ajax) in the .ts file,

      hitAnchor1(e){
          console.log("Events", e);
          alert("You have clicked the anchor-1 tag");
       }
      hitAnchor2(e){
          console.log("Events", e);
          alert("You have clicked the anchor-2 tag");
       }
    

    That's all. It work's as expected. I created the example below, You can have a look:-

    https://stackblitz.com/edit/angular-yn6q6t

    0 讨论(0)
提交回复
热议问题