Passive Link in Angular 2 - equivalent

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

    Updated for Angular2 RC4:

    import {HostListener, Directive, Input} from '@angular/core';
    
    @Directive({
        selector: '[href]'
    })
    export class PreventDefaultLinkDirective {
    
        @Input() href;
        @HostListener('click', ['$event']) onClick(event) {this.preventDefault(event);}
    
        private preventDefault(event) {
            if (this.href.length === 0 || this.href === '#') {
                event.preventDefault();
            }
        }
    }
    

    Using

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

提交回复
热议问题