Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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

like image 604
rcarrington Avatar asked Apr 20 '16 19:04

rcarrington


People also ask

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.

What is the use of routerLink in angular?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

Can we give routerLink to div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.


3 Answers

Or you can simply add a condition to the attribute.

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

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

like image 129
fifix Avatar answered Oct 19 '22 18:10

fifix


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

like image 33
Boies Ioan Avatar answered Oct 19 '22 18:10

Boies Ioan


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>
like image 10
Jonathan Dudley Avatar answered Oct 19 '22 18:10

Jonathan Dudley