52

I'm trying to implement routerLinkActive to my app but i'm facing the issue that it's sets class active to multiple links. Here's how i'm doing it

<ul class="nav nav-tabs">
  <li role="presentation" [routerLinkActive]="['active']"><a [routerLink]="['/']">Home</a></li>
  <li role="presentation" [routerLinkActive]="['active']"><a [routerLink]="['/about']">About</a></li>
  <li role="presentation" [routerLinkActive]="['active']"><a [routerLink]="['/contact']" >Contact Us</a></li>  
</ul>

Here it's how it looks

enter image description here Here it's how it look in dev-tools enter image description here And my address bar

enter image description here

Am i missing something because i'm doing as explained in angular docs.

Community
  • 1
  • 1
Jorawar Singh
  • 7,463
  • 4
  • 26
  • 39

1 Answers1

154

Try to set [routerLinkActiveOptions]="{exact: true}" to HTML as below :

<ul class="nav nav-tabs">
  <li role="presentation" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"><a [routerLink]="['/']">Home</a></li>
  <li role="presentation" routerLinkActive="active"><a [routerLink]="['/about']">About</a></li>
  <li role="presentation" routerLinkActive="active"><a [routerLink]="['/contact']" >Contact Us</a></li>  
</ul>

How does it work ?##

RouterLinkActive does chunk the current route and try to match it's parts with the RouterLinks you've provided. With that in mind, route / will be matched anywhere as it's the very parent for all the other routes (like /about, /contact, etc. as it consist of / + route-path). To simplify, it's not a bug, it's sometimes a needed functionality in your application to match multiple routes. To prevent that, you can specify the routerLinkActiveOptions to match exactly the route you're on. That means it's not going to match parent routes but will only try to find the routerLink provided for this exact route.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
  • 3
    it works because for 1st link url will be "localhost:8080/" and for 2nd link URL is "localhost:8080/about" and if for 1st link if you do not add `routerLinkActiveOptions` then when you visit `localhost:8080/about` page then also it will match starting url "localhost:8080/" and because of it, it sets active class on first link. you have to set `routerLinkActiveOptions` for those URL only for which you want the url matches the link exactly. – ranakrunal9 Aug 29 '16 at 05:25