1

I am trying to add routerLink to an anchor tag dynamically based on if a routerLink is passed to the component itself.

This is the code I currently have:

[attr.routerLink]="router ? router : null"

The resulting markup looks like this when a routerLink is passed, but no href is passed:

<a _ngcontent-hlo-122="" routerlink="/myRoute">My Link</a>

I've tried this out a number of ways, but I can never seem to get this to work. Does anyone have a solid solution to this problem?

StephenRios
  • 2,192
  • 4
  • 26
  • 42
  • routerLink is an angular directive not element property. – Haddar Macdasi Mar 22 '17 at 21:47
  • I'm aware of that, I've tried this with a ternary operator as well, but there is not a value to put on the other side that doesn't throw an error when the routerLink passed to the component is null, undefined, or not valid. `[attr.routerLink]="router ? router : null"` – StephenRios Mar 22 '17 at 21:48
  • AFAIK you can't apply `routerLink` conditionally. I've managed to workaround this using the @Gunter's answer [here](http://stackoverflow.com/questions/35431188/angular-2-disable-routerlink) – Garth Mason Mar 23 '17 at 01:25

1 Answers1

2

Finally found the answer here.

Solution:

<a [routerLink]="router ? [router] : []>My Router Link</a>
Community
  • 1
  • 1
StephenRios
  • 2,192
  • 4
  • 26
  • 42