Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

angular - Why Angular2 routerLinkActive sets active class to multiple links?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...