RouterLinkActive is not working when using a dynamically generated link when navigating through the app itself.
e.g. in my top navigation i have this;
<a [routerLink]=['user', currentUser.name] routerLinkActive='active'>{{currentUser.name}}</a>
Whilst the hardcoded version would work.
<a [routerLink]=['user','bob']>View Bobs Account</a>
A plunk for this is here; https://plnkr.co/edit/BYKMucE3Y75uJSpV5VWx?p=preview
Click on "John" and "Dynamic Router Link Name = " and "John" should both be active. This sometimes work on the first click, if so, then click back to "Home", the click again on "John", you'll see only the hardcoded link is registered as active, even though the hrefs are identical.
Is this designed/impossible? or am i setting something incorrectly?
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.
RouterLinkActivelinkTracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.
Yes it can be attached to div tag, your route is probably wrong try add / in front of route.
RouterLink for dynamic dataDynamic data or user-defined objects can be passed from Angular version 7.2 using the state object stored in History API. The state value can be provided using the routerLink directive or navigateByURL.
In your component:
import {Router} from '@angular/router'; isActive(instruction: any[]): boolean { // Set the second parameter to true if you want to require an exact match. return this.router.isActive(this.router.createUrlTree(instruction), false); }
In your HTML:
<a [class.active]="isActive(['user', currentUser.name])">
Router.isActive()
documentation on angular.io
Accepted answer didn't work for me and I just wanted to highlight top level route matches so I used:
isActive(url): boolean { return this.router.url.includes(url); }
and:
[class.active]="isActive('url')"
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