Angular Js

How to styling Active Router Link in Angular?

How to styling Active Router Link in Angular?

How active route works In Angular?

This Article helps you to understand, how do you determine the active route  In Angular? How to Apply CSS to active router link?


The user can distinguish between active and inactive router links by styling the active router link in angular. To interact with active router links, Angular offers a unique approach.

Approach:
Create the Angular app to be used.
Create the header component that contains the navigation links.
Apply "routerLinkActive" to each router link after that, and give this property a CSS class. In this CSS file, we've created the "active" class.
Provide the { exact : true } to the root route to avoid multiple active router links.


Navigation in Header Component

<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've provided "routerLinkActive," which is routing capability that turns on the current route automatically. We also had to supply the CSS class. Active is a CSS class that was automatically assigned to the activated route in this case where routerLinkActive = "active".


Header.component.css


.active{
  background: 'white'
}


But above scenario it still creates a problem here. Because of the way "routerLinkActive" functions, our Home route is always active even when we travel to another route. In order to deal with this, angular provides another directive referred to as routerLinkActiveOptions. The home route operates on "localhost:4200/" and other routes are "localhost:4200/about." As a result, "routerLinkActive" finds "localhost:4200/" inside every other route and the Home router link is always active.


lets modify our above template

<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, for the Home component, routerLinkActiveOptions only permits the exact path match as an active route..



Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram