Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RouterLinkActive for RouterLink with parameters (/dynamic)

Tags:

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?

like image 713
ct5845 Avatar asked Sep 01 '16 12:09

ct5845


People also ask

What is routerLink and routerLinkActive?

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.

What is the routerLinkActive directive used for?

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.

Can we give routerLink to div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.

Can we pass object in routerLink?

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.


2 Answers

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

like image 139
Victor Bredihin Avatar answered Jan 04 '23 00:01

Victor Bredihin


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')" 
like image 37
Tanya Branagan Avatar answered Jan 04 '23 00:01

Tanya Branagan