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

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


Specifying pointer-events: none in CSS disables mouse input but doesn't disable keyboard input. For example, the user can still tab to the link and "click" it by pressing the Enter key or (in Windows) the ≣ Menu key. You could disable specific keystrokes by intercepting the keydown event, but this would likely confuse users relying on assistive technologies.

Probably the best way to disable a link is to remove its href attribute, making it a non-link. You can do this dynamically with a conditional href attribute binding:

<a *ngFor="let link of links"   [attr.href]="isDisabled(link) ? null : '#'"   [class.disabled]="isDisabled(link)"   (click)="!isDisabled(link) && onClick(link)">   {{ link.name }}</a>

Or, as in Günter Zöchbauer's answer, you can create two links, one normal and one disabled, and use *ngIf to show one or the other:

<ng-template ngFor #link [ngForOf]="links">    <a *ngIf="!isDisabled(link)" href="#" (click)="onClick(link)">{{ link.name }}</a>    <a *ngIf="isDisabled(link)" class="disabled">{{ link.name }}</a></ng-template>

Here's some CSS to make the link look disabled:

a.disabled {    color: gray;    cursor: not-allowed;    text-decoration: underline;}


For [routerLink] you can use:

Adding this CSS should do what you want:

a.disabled {   pointer-events: none;   cursor: not-allowed; }

This should fix the issue mentioned by @MichelLiu in the comments:

<a href="#" [class.disabled]="isDisabled(link)"    (keydown.enter)="!isDisabled(link)">{{ link.name }}</a>

Another approach

<a [routerLink]="['Other']" *ngIf="!isDisabled(link)">{{ link.name }}</a><a  *ngIf="isDisabled(link)">{{ link.name }}</a>  

Plunker example


My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/