Passive Link in Angular 2 - equivalent

后端 未结 16 2741
谎友^
谎友^ 2020-12-04 13:36

In Angular 1.x I can do the following to create a link which does basically nothing:

My Link

But the same tag

相关标签:
16条回答
  • 2020-12-04 14:22

    An achor should navigate to something, so I guess the behaviour is correct when it routes. If you need it to toggle something on the page it's more like a button? I use bootstrap so I can use this:

    <button type="button" class="btn btn-link" (click)="doSomething()">My Link</button>
    
    0 讨论(0)
  • 2020-12-04 14:25

    Here are some ways to do it:

    • <a href="" (click)="false">Click Me</a>

    • <a style="cursor: pointer;">Click Me</a>

    • <a href="javascript:void(0)">Click Me</a>

    0 讨论(0)
  • 2020-12-04 14:27

    A really simple solution is not to use an A tag - use a span instead:

    <span class='link' (click)="doSomething()">Click here</span>
    
    span.link {
      color: blue;
      cursor: pointer;
      text-decoration: underline;
    }
    
    0 讨论(0)
  • 2020-12-04 14:27

    You have prevent the default browser behaviour. But you don’t need to create a directive to accomplish that.

    It’s easy as the following example:

    my.component.html

    <a href="" (click)="goToPage(pageIndex, $event)">Link</a>
    

    my.component.ts

    goToPage(pageIndex, event) {
      event.preventDefault();
      console.log(pageIndex);
    }
    
    0 讨论(0)
  • 2020-12-04 14:30

    If you have Angular 5 or above, just change

    <a href="" (click)="passTheSalt()">Click me</a>
    

    into

    <a [routerLink]="" (click)="passTheSalt()">Click me</a>
    

    A link will be displayed with a hand icon when hovering over it and clicking it won't trigger any route.

    Note: If you want to keep the query parameters, you should set queryParamsHandling option to preserve:

    <a [routerLink]=""
       queryParamsHandling="preserve"
       (click)="passTheSalt()">Click me</a>
    
    0 讨论(0)
  • 2020-12-04 14:30

    That will be same, it doesn't have anything related to angular2. It is simple html tag.

    Basically a(anchor) tag will be rendered by HTML parser.

    Edit

    You can disable that href by having javascript:void(0) on it so nothing will happen on it. (But its hack). I know Angular 1 provided this functionality out of the box which isn't seems correct to me now.

    <a href="javascript:void(0)" >Test</a>
    

    Plunkr


    Other way around could be using, routerLink directive with passing "" value which will eventually generate blank href=""

    <a routerLink="" (click)="passTheSalt()">Click me</a>
    
    0 讨论(0)
提交回复
热议问题