Passive Link in Angular 2 - equivalent

后端 未结 16 2787
谎友^
谎友^ 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.

提交回复
热议问题