RouterLinkActive sets active class to Multiple Links

RouterLinkActive active class

As web developer sometimes you might have faced the issue of routerLinkActive setting active class to multiple links in your angular application. What routerLinkActive is? It tracks 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. In other words, an active class is added to show that the link is active now.

Example of RouterLinkActive usage.

The following is the normal way of usage.

<a routerLink="/home" routerLinkActive="active">Home</a>
<a routerLink="/contact" routerLinkActive="active">Contact Us</a>

But, sometimes when you are working with modules, you might have observed that two links are active which rout to the same module folder and sub folder. For example, “application/news” and “application/news/latest-news” are two links and both these links are in the the same list in navigation panel. Sometimes you can see when you go to the latest-news page, both links are active at the same time. See the below example.

The Scenario

<pre>
<ul>
<li>
<a routerLink="application/news" routerLinkActive="active">News</a>
</l>
<li>
<a routerLink="application/news/latest-news" routerLinkActive="active">Latest News</a>
</li>
</pre>

The above example code may give both links as active links when we are in the ‘Latest news’ page. How we can fix? Or what we can do to make only the expected link to be active. See the following code.

<pre>
<a routerLink="/application/news/latest-news" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">Latest News</a>
</pre>

[routerLinkActiveOptions]=”{exact:
true}” is used to add the active class only when the URL matches the link exactly. True or false values can be used based on the requirement.

label,

About the author