typescript 46 lines · 6 steps

Building an active-route navbar in Angular

A standalone Angular navbar that highlights the current route and exposes it to assistive tech.

Explained by highlit
1import { Component } from '@angular/core';
2import { RouterLink, RouterLinkActive } from '@angular/router';
3import { NgFor } from '@angular/common';
4 
5@Component({
6 selector: 'app-navbar',
7 standalone: true,
8 imports: [RouterLink, RouterLinkActive, NgFor],
9 template: `
10 <nav class="navbar">
11 <a
12 routerLink="/"
13 routerLinkActive="active"
14 [routerLinkActiveOptions]="{ exact: true }"
15 >
16 Home
17 </a>
18 
19 <a
20 *ngFor="let link of links"
21 [routerLink]="link.path"
22 routerLinkActive="active"
23 #rla="routerLinkActive"
24 [attr.aria-current]="rla.isActive ? 'page' : null"
25 >
26 {{ link.label }}
27 </a>
28 </nav>
29 `,
30 styles: [`
31 .navbar { display: flex; gap: 1rem; }
32 .navbar a { color: #556; text-decoration: none; padding: 0.5rem 0.75rem; }
33 .navbar a.active {
34 color: #1a73e8;
35 font-weight: 600;
36 border-bottom: 2px solid #1a73e8;
37 }
38 `],
39})
40export class NavbarComponent {
41 readonly links = [
42 { path: '/dashboard', label: 'Dashboard' },
43 { path: '/projects', label: 'Projects' },
44 { path: '/settings', label: 'Settings' },
45 ];
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1routerLinkActive toggles a CSS class automatically based on the current URL, so highlighting needs no manual state.
  2. 2Exporting a directive to a template reference variable lets you read its live state elsewhere in the template.
  3. 3Deriving aria-current from active state keeps the UI accessible without duplicating routing logic.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an active-route navbar in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code