Attaching click to anchor tag in angular

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

    You can try something like this:

    <a href="javascript: void(0);" (click)="method()">
    

    OR

    <a href="javascript: void(0);" [routerLink]="['/abc']">
    
    0 讨论(0)
  • 2020-12-13 12:58

    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.

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

    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!

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

    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 }
    ]
    
    0 讨论(0)
  • 2020-12-13 13:03

    I had to combine several of the answers to get a working solution.

    This solution will:

    • Style the link with the appropriate 'a' styles.
    • Call the desired function.
    • Not navigate to http://mySite/#

      <a href="#" (click)="!!functionToCall()">Link</a>

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

    I was able to implement this successfully

    <a [routerLink]="['/login']">abc</a>
    
    0 讨论(0)
提交回复
热议问题