Angular routerLinkActive for multiple paths

Sam picture Sam · Mar 5, 2018 · Viewed 11.6k times · Source

In my Angular 5 project I've got a bootstrap nav-bar menu. routerLinkActive does work nicely when the start of the path matches the routerlink of the menu, like:

<li [routerLinkActive]="['active']">
  <a [routerLink]="['/entity/teacher']">Teacher</a>
</li>

the Code above activates the menu item nicely for `/entity/teacher/add' and more

Problem is, I've got a Kind of 'catch-all' navigation item which contains things which do not line up:

<li [routerLinkActive]="['active']">
  <a [routerLink]="['/config']">Configuration</a>
</li>

I want this item to highlight for the paths /tasks and /entity/settings, too, not only for /config.

Problem is, I can't change the routing of the app. How do I get the menu item to line up for other routing paths as well as the one in the routerLink?

Answer

Teddy Sterne picture Teddy Sterne · Mar 5, 2018

You can use a template reference variable to get a reference to the outer routes and then apply the class when they are active. You can either link them to an existing routerLinkActive element or to a hidden one. Here is an example using the hidden method.

<li routerLinkActive="active" [ngClass]="{'active': tasksActive.isActive || settingsActive.isActive }">
  <a [routerLink]="['/config']">Configuration</a>
</li>
<a routerLink="/tasks" routerLinkActive #tasksActive="routerLinkActive" style="display: none"></a>
<a routerLink="/entity/settings" routerLinkActive #settingsActive="routerLinkActive" style="display: none"></a>