Conditionally add RouterLink or other attribute directives to an element in Angular 2

Or you can simply add a condition to the attribute.

<button [routerLink]="myVar ? ['/myScreen'] : []"></button>

Redirect to '/myScreen' only if myVar is true.


As far as I know, there is no straight way to do this. There are some workarounds... I used something like this:

<button *ngIf="condition" [routerLink]="['SomeRoute']"></button>
<button *ngIf="!condition"></button>

There is an similar discussion here: link


If you don't want to duplicate the element, and just want to prevent clicks depending on the condition, you could do the following:

<button 
  [style.pointer-events]="condition ? 'auto' : 'none'" 
  routerLink="/some/route"
>
</button>

Tags:

Angular