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
The RouterLinkActive is a directive for adding or removing classes from an HTML element that is bound to a RouterLink . Using this directive, we can toggle CSS classes for active Router Links based on the current RouterState . The main use case of this directive is to highlight which route is currently active.
Create the header component that contains the navigation links. Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file. Provide the { exact : true } to the root route to avoid multiple active router links.
Show activity on this post. You can check the current route by injecting the Location object into your controller and checking the path() , like so: class MyController { constructor(private location:Location) {} ...
With routerLinkActiveOptions you can pass a javascript object {exact:true} to direct Angular to make link active only when exact path matches. With this configuration change 'Home' menu will only be highlighted when it is selected, as soon as you move away from this option it won't remain highlighted anymore.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With