Passive Link in Angular 2 - equivalent

后端 未结 16 2740
谎友^
谎友^ 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})]);
    
    0 讨论(0)
  • 2020-12-04 14:16

    you need to prevent event's default behaviour as follows.

    In html

    <a href="" (click)="view($event)">view</a>
    

    In ts file

    view(event:Event){
     event.preventDefault();
     //remaining code goes here..
    }
    
    0 讨论(0)
  • 2020-12-04 14:17

    I have 4 solutions for dummy anchor tag.

        1. <a style="cursor: pointer;"></a>
        2. <a href="javascript:void(0)" ></a>
        3. <a href="current_screen_path"></a>
    

    4.If you are using bootstrap:

    <button class="btn btn-link p-0" type="button" style="cursor: pointer"(click)="doSomething()">MY Link</button>
    
    0 讨论(0)
  • 2020-12-04 14:17

    I wonder why no one is suggesting routerLink and routerLinkActive (Angular 7)

    <a [routerLink]="[ '/resources' ]" routerLinkActive="currentUrl!='/resources'">
    

    I removed the href and now using this. When using href, it was going to the base url or reloading the same route again.

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

    simeyla solution:

    <a href="#" (click)="foo(); false">
    <a href="" (click)="false">
    
    0 讨论(0)
  • 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();
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题