angularangular2-routing

How can I conditionally disable the routerLink attribute?


In my Angular 2 application I'm trying to disable a routerLink without any success. I've tried to handle the click event on the click event (with event.preventDefault() and event.stopPropagation()) but it doesn't work.

How can I disable a routerLink?


Solution

  • Disable pointer-events on the element via CSS:

    <a [routerlink]="xxx" [class.disabled]="disabled ? true : null">Link</a>
    
    a.disabled {
       pointer-events: none;
       cursor: default;
    }
    

    See also Angular2, what is the correct way to disable an anchor element?

    or

    <a *ngIf="isEnabled" [routerlink]="xxx">Link</a>
    <div *ngIf="!isEnabled">not a link</div>
    

    or to easily reuse the disabled link template

    <ng-template #disabledLink>
      <div *ngIf="!isEnabled">not a link</div>
    </ng-template>
    <a *ngIf="isEnabled; else disabledLink" [routerLink]="xxx">Link</a>