Conditionally add RouterLink or other attribute di

2020-02-26 15:34发布

问题:

In Angular 2 if I have an element like <button></button> how can I conditionally add an attribute directive like [routerLink]="['SomeRoute'] to it?

回答1:

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



回答2:

Or you can simply add a condition to the attribute.

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

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



回答3:

   <div [ngClass] ='{"disabled-link":!isMicrositeEnable,"cursor-pointer":"isMicrositeEnable"}' [routerLink]="isMicrositeEnable ? ['/microsite'] : []">


回答4:

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>


标签: angular