Sub topic 4
Navigating with RouterLink and Highlighting Active Links
This chapter assumes you already have a Routes array registered with provideRouter and a <router-outlet /> in your root component. Here you connect the two: you give users links that change the URL without reloading the page, and you style whichever link matches the current URL. You should be comfortable with standalone components, template binding syntax, and the imports array.
Why a plain `href` is not enough
A normal <a href="/home"> makes the browser send a fresh request to the server. The server returns index.html, Angular boots again, and all in-memory state is lost: service data, form input, and scroll position. It works, but it throws away most of what a single-page application gives you.
The RouterLink directive handles the click inside the app instead. On an anchor element it does these things:
- It computes a URL from its input and writes it into the element's
hrefattribute. Hover previews, "copy link address", and middle-click to open in a new tab all keep working. - On a plain left click it calls
preventDefault()and asks theRouterto navigate. - On a modified click (Ctrl, Cmd, Shift, or middle button) it does nothing, so the browser opens the
hrefin a new tab or window the normal way.
A complete working example
The following file defines three small pages, a route table, and a root component with a nav bar. You can paste it into a fresh src/main.ts in an Angular 17+ project and run ng serve.
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
provideRouter,
Routes,
RouterLink,
RouterLinkActive,
RouterOutlet,
} from '@angular/router';
@Component({ selector: 'app-home', standalone: true, template: `<h2>Home</h2>` })
class HomeComponent {}
@Component({ selector: 'app-products', standalone: true, template: `<h2>All products</h2>` })
class ProductListComponent {}
@Component({ selector: 'app-product', standalone: true, template: `<h2>One product</h2>` })
class ProductDetailComponent {}
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', component: ProductListComponent },
{ path: 'products/:id', component: ProductDetailComponent },
];
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
styles: [`.active { font-weight: bold; text-decoration: underline; }`],
template: `
<nav>
<a routerLink="/" routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }"
ariaCurrentWhenActive="page">Home</a>
<a routerLink="/products" routerLinkActive="active"
ariaCurrentWhenActive="page">Products</a>
<a [routerLink]="['/products', 42]" routerLinkActive="active"
ariaCurrentWhenActive="page">Product 42</a>
</nav>
<router-outlet />
`,
})
class AppComponent {}
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
});Click "Product 42". Both "Products" and "Product 42" turn bold, and "Home" does not. The sections below explain why.
The two forms of `routerLink`
String form
routerLink="/products" passes a literal string. Angular parses it as a URL, so routerLink="/products/42?sort=asc" also works. Use this form for fixed destinations.
Link parameters array
[routerLink]="['/products', product.id]" passes an array. Each element becomes one or more path segments, and the router encodes each one. This form is the safe choice whenever part of the path comes from data:
| Binding | Resulting URL |
|---|---|
| `['/products', 42]` | `/products/42` |
| `['/products', 'a b']` | `/products/a%20b` |
| `['/products', 'x/y']` | `/products/x%2Fy` |
| `'/products/' + 'x/y'` (string) | `/products/x/y` (two segments) |
The last row shows a common bug. Building the URL by string concatenation lets a slash inside the value split into extra segments, so the link may hit the wrong route.
Query parameters and fragments are set with the separate queryParams and fragment inputs, which have their own chapter later in this tutorial. Reading the :id value on the destination side is covered in the route parameters chapter.
Absolute and relative links
A path that starts with / is absolute: it resolves from the application root. A path without a leading slash is relative, and it resolves against the route of the component whose template contains the link. The directive injects ActivatedRoute to get that route.
Suppose ProductDetailComponent is rendered at /products/42 and its template contains:
| Link | Resolves to |
|---|---|
| `routerLink="reviews"` | `/products/42/reviews` |
| `routerLink="../43"` | `/products/43` |
| `routerLink="../.."` | `/` |
| `routerLink="./reviews"` | `/products/42/reviews` |
Relative links make a feature reusable. A product area can move from /products to /shop/products without editing any links inside it.
`routerLink` on elements that are not anchors
You can put routerLink on a <button>, <li>, or any element. Clicking it still navigates, but there is no href, so the user loses middle-click, "open in new tab", and the browser's link semantics. Screen readers also announce a button, not a link. Use anchors for navigation and buttons for actions.
To disable a link, bind null or undefined: [routerLink]="canEdit ? 'edit' : null". On an anchor this removes the href as well.
Highlighting the active link with `RouterLinkActive`
RouterLinkActive watches router navigation events. After each navigation it checks whether any RouterLink it is linked to matches the current URL, and adds or removes CSS classes on its host element.
You can pass classes as a space-separated string or an array:
<a routerLink="/products" routerLinkActive="active nav-current">Products</a>
<a routerLink="/products" [routerLinkActive]="['active', 'nav-current']">Products</a>Subset matching is the default
By default a link counts as active when its path is a prefix of the current URL, measured in whole segments. At /products/42, the link /products is active because products is the first segment. The link /prod is not, because matching uses segments, not characters.
This explains the behaviour in the example. It also explains the most frequently reported issue: a link to / is active on every page, because the empty path is a prefix of every URL. Add [routerLinkActiveOptions]="{ exact: true }" to the root link, as the example does.
Fine-grained matching options
{ exact: true } is shorthand. For full control, pass an IsActiveMatchOptions object:
<a routerLink="/products"
[queryParams]="{ view: 'grid' }"
routerLinkActive="active"
[routerLinkActiveOptions]="{
paths: 'exact',
queryParams: 'ignored',
matrixParams: 'ignored',
fragment: 'ignored'
}">Grid</a>| Option | Allowed values | Default with `exact: false` | Default with `exact: true` |
|---|---|---|---|
| `paths` | `'exact'`, `'subset'` | `'subset'` | `'exact'` |
| `queryParams` | `'exact'`, `'subset'`, `'ignored'` | `'subset'` | `'exact'` |
| `matrixParams` | `'exact'`, `'subset'`, `'ignored'` | `'ignored'` | `'ignored'` |
| `fragment` | `'exact'`, `'ignored'` | `'ignored'` | `'ignored'` |
The query parameter default often causes trouble. With exact: true, a "Products" link stops being active as soon as the user adds ?page=2. Use paths: 'exact', queryParams: 'ignored' when only the path should decide.
Activating a parent element
RouterLinkActive does not need to sit on the link itself. It finds every RouterLink among its content children and becomes active if any of them match:
<li routerLinkActive="open">
<a routerLink="/admin/users">Users</a>
<a routerLink="/admin/roles">Roles</a>
</li>The <li> gets the open class while the user is on either admin page. This is useful for expanding a menu section.
Reading the active state in the template
The directive is exported as routerLinkActive, so a template reference variable gives you its isActive flag:
<a routerLink="/inbox" routerLinkActive="active" #rla="routerLinkActive">
Inbox
@if (rla.isActive) { <span aria-hidden="true">●</span> }
</a>For side effects in the component class, use the (isActiveChange) output, which emits a boolean each time the state flips.
Accessibility: `ariaCurrentWhenActive`
The CSS class is visual only. Set ariaCurrentWhenActive="page" and the directive adds aria-current="page" to the active link and removes it from the others, so assistive technology announces the current page. Other accepted values are 'step', 'location', 'date', 'time', true, and false. You can also style with a[aria-current="page"] and drop the extra class.
Common errors and how to spot them
| Symptom | Likely cause |
|---|---|
| Clicking reloads the whole app | Used `href` instead of `routerLink` |
| Link does nothing and has no `href` | `RouterLink` missing from the component's `imports`. A static `routerLink="/x"` attribute then fails silently |
| Error "Can't bind to 'routerLink'" | `RouterLink` missing from `imports`, with a property binding `[routerLink]` |
| Home link is always highlighted | Root link without `exact: true` |
| Classes never applied | `RouterLinkActive` not imported, or no `RouterLink` inside its element |
| Shared header link goes to the wrong place | Relative path resolved against the header's route, not the current URL |
| Active link loses its style when a query param is added | `exact: true` also matches query params exactly |
Exercise
A sidebar lives in AppComponent and contains <a routerLink="/" routerLinkActive="active">Dashboard</a> and <a routerLink="/reports" routerLinkActive="active">Reports</a>. At /reports/2025, both links are bold. What is wrong, and how do you fix it so only Reports is bold, and Reports stays bold at /reports/2025?
Show answer
The Dashboard link uses the default subset matching, and the empty root path is a prefix of every URL, so it is always active. Add [routerLinkActiveOptions]="{ exact: true }" to the Dashboard link only. Leave Reports on the default subset matching so it stays active for /reports/2025.
Exercise
Inside a component rendered at /teams/7/members, a template contains <a routerLink="../settings">Settings</a> and <a [routerLink]="['/teams', team.slug]">Team</a>, where team.slug is "r&d/east". What URLs do the two links produce?
Show answer
The first resolves against the component's route, /teams/7/members. Going up one segment gives /teams/7, so the link points to /teams/7/settings. The second is absolute. The router encodes the slug as a single segment, giving /teams/r%26d%2Feast. The slash does not split the slug into two segments.
Exercise
You want a "Products" link to be highlighted at /products and /products?page=3, but not at /products/42. Write the routerLinkActiveOptions value.
Show answer
{ paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }. With paths set to 'exact', /products/42 does not match. With queryParams set to 'ignored', ?page=3 does not stop the link from being active. Plain { exact: true } would not work, because it also requires the query parameters to match exactly.