Why Angular2 routerLinkActive sets active class to multiple links?

余生长醉 提交于 2019-11-27 15:47:00

问题


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

Here it's how it look in dev-tools And my address bar

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


回答1:


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 found the routerLink provided for this exact route.



来源:https://stackoverflow.com/questions/39181539/why-angular2-routerlinkactive-sets-active-class-to-multiple-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!