Open In App

Styling Active Router Link in Angular

Styling the active router link in angular allows the user to differentiate between the active router link and inactive router links. Angular provides a special mechanism to work with active router links. 

Approach: 



Syntax:

<a routerLink="/" routerLinkActive="active" >Home</a>


 

Example: We have created the header component with specified routes.




<span>
    <ul>
        <li><a routerLink="/" routerLinkActive="active">
            Home
        </a></li>
        <li><a routerLink="/products" 
            routerLinkActive="active">Products
        </a></li>
        <li><a routerLink="/about" 
            routerLinkActive="active">About Us
        </a></li>
        <li><a routerLink="/contact" 
            routerLinkActive="active">Contact Us
        </a></li>
    </ul>
</span>
<router-outlet></router-outlet>

Here we have provided the “routerLinkActive” which is routing functionality that automatically activate the current route, and we have to provide the CSS class as well. Here in routerLinkActive = “active” active is a CSS class that automatically applied to the activated route.




.active{
    background: 'white'
}

But here, it still causes an issue our Home route is always active even we navigate to some other route the reason behind this is the way “routerLinkActive” works. The home route works on “localhost:4200/” and other routes are “localhost:4200/about” so “routerLinkActive” finds “localhost:4200/” inside every other route and the Home router link is always active to deal with this angular provide another directive called routerLinkActiveOptions.

Updated




<span>
    <ul>
        <li><a routerLink="/" routerLinkActive="active" 
            [routerLinkActiveOptions]={exact:true}>Home
        </a></li>
        <li><a routerLink="/products" 
            routerLinkActive="active">Products
        </a></li>
        <li><a routerLink="/about" 
            routerLinkActive="active">About Us
        </a></li>
        <li><a routerLink="/contact" 
            routerLinkActive="active">Contact Us
        </a></li>
    </ul>
</span>
<router-outlet></router-outlet>

So routerLinkActiveOptions allow only the exact path match as an active route for the Home component.

Output:


Article Tags :