Why Angular2 routerLinkActive sets active class to multiple links?

前端 未结 1 1293
无人及你
无人及你 2020-12-09 14:50

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

相关标签:
1条回答
  • 2020-12-09 15:10

    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.

    0 讨论(0)
提交回复
热议问题