Passive Link in Angular 2 - equivalent

后端 未结 16 2742
谎友^
谎友^ 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:31

    There are ways of doing it with angular2, but I strongly disagree this is a bug. I'm not familiarized with angular1, but this seems like a really wrong behavior even though as you claim is useful in some cases, but clearly this should not be the default behavior of any framework.

    Disagreements aside you can write a simple directive that grabs all your links and check for href's content and if the length of it it's 0 you execute preventDefault(), here's a little example.

    @Directive({
      selector : '[href]',
      host : {
        '(click)' : 'preventDefault($event)'
      }
    })
    class MyInhertLink {
      @Input() href;
      preventDefault(event) {
        if(this.href.length == 0) event.preventDefault();
      }
    }
    

    You can make it to work across your application by adding this directive in PLATFORM_DIRECTIVES

    bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: MyInhertLink, multi: true})]);
    

    Here's a plnkr with an example working.

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

    I am using this workaround with css:

    /*** Angular 2 link without href ***/
    a:not([href]){
        cursor: pointer; 
        -webkit-user-select: none; 
        -moz-user-select: none; 
        user-select: none
    }
    

    html

    <a [routerLink]="/">My link</a>
    

    Hope this helps

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

    In my case deleting href attribute solve problem as long there is a click function assign to a.

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

    Here is a simple way

      <div (click)="$event.preventDefault()">
                <a href="#"></a>
       </div>
    

    capture the bubbling event and shoot it down

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