0
0
AngularHow-ToBeginner · 3 min read

How to Use routerLinkActive in Angular for Active Link Styling

Use routerLinkActive on an element to add a CSS class when its linked route is active. It highlights navigation links automatically by toggling the specified class based on the current URL.
📐

Syntax

The routerLinkActive directive is added to an HTML element to apply a CSS class when the linked route is active. You specify the class name(s) as a string or array.

  • routerLinkActive="active-class": Adds active-class when the route matches.
  • [routerLinkActiveOptions]="{ exact: true }": Optional to match the route exactly.
html
<a routerLink="/home" routerLinkActive="active-link" [routerLinkActiveOptions]="{ exact: true }">Home</a>
💻

Example

This example shows a simple navigation bar where the active link is highlighted with a CSS class named active-link. The class is added automatically when the route matches the link.

html
<!-- app.component.html -->
<nav>
  <a routerLink="/home" routerLinkActive="active-link" [routerLinkActiveOptions]="{ exact: true }">Home</a>
  <a routerLink="/about" routerLinkActive="active-link">About</a>
  <a routerLink="/contact" routerLinkActive="active-link">Contact</a>
</nav>

<!-- app.component.css -->
.active-link {
  font-weight: bold;
  color: #007bff;
  text-decoration: underline;
}
Output
A navigation bar with three links: Home, About, Contact. The active link is bold, blue, and underlined.
⚠️

Common Pitfalls

Common mistakes include:

  • Not using [routerLinkActiveOptions]="{ exact: true }" when you want to highlight only the exact route, causing multiple links to appear active.
  • Placing routerLinkActive on a child element instead of the link element, so the class does not toggle correctly.
  • Forgetting to add the CSS class styles, so the active state is not visible.
html
<!-- Wrong: routerLinkActive on a span inside the link -->
<a routerLink="/home"><span routerLinkActive="active-link">Home</span></a>

<!-- Right: routerLinkActive on the anchor tag -->
<a routerLink="/home" routerLinkActive="active-link">Home</a>
📊

Quick Reference

Directive / OptionPurpose
routerLinkActive="class-name"Adds the CSS class when the route is active
[routerLinkActiveOptions]="{ exact: true }"Matches the route exactly, not partially
routerLink="/path"Defines the route path for navigation

Key Takeaways

Add routerLinkActive to links to toggle CSS classes based on active routes.
Use routerLinkActiveOptions with exact: true to highlight only exact route matches.
Place routerLinkActive on the element with routerLink for correct behavior.
Define CSS styles for the active class to see visual feedback.
routerLinkActive helps create clear navigation highlighting automatically.