Open In App

Styling Active Router Link in Angular

Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  • Create the Angular app to be used.
  • Create the header component that contains the navigation links.
  • Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file.
  • Provide the { exact : true } to the root route to avoid multiple active router links.

Syntax:

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

 

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

header.component.html




<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.

header.component.css




.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

header.component.htm




<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:



Last Updated : 17 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads