Passive Link in Angular 2 - equivalent

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

    Updated for Angular 5

    import { Directive, HostListener, Input } from '@angular/core';
    
    @Directive({
      // tslint:disable-next-line:directive-selector
      selector : '[href]'
    })
    export class HrefDirective {
      @Input() public href: string | undefined;
    
      @HostListener('click', ['$event']) public onClick(event: Event): void {
        if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
          event.preventDefault();
        }
      }
    }
    

提交回复
热议问题