Blog

Part 16 · Routing in Angular: Routes, routerLink, Params as Inputs and Lazy Loading

Routing gives each page of an app its own URL. This part covers routes, the outlet, routerLink, routerLinkActive, a not-found page, route parameters as inputs, lazy pages and route providers.

Every app so far has been one screen. Real apps have pages: a list, a detail page, a settings page. Each page should have its own address, so you can bookmark it, share it and press Back. Angular’s router does that. It reads the URL, picks the component for it, and shows it, without reloading the page.

This part covers routes, <router-outlet>, routerLink, routerLinkActive, a not-found page, route parameters read as inputs, pages that load only when someone visits them, and a route with its own providers, which Part 14 promised. It builds on inputs from Part 5 and services from Part 13. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

This app has two pages. The home page has a counter. The about page has one line of text. Make these four files. Each page is an ordinary component:

// src/app/home.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="count.update((n) => n + 1)">Add one</button>
  `,
})
export class Home {
  protected readonly count = signal(0);
}
// src/app/about.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-about',
  template: `<p>This app counts things.</p>`,
})
export class About {}

The routes say which component goes with which URL. Replace the empty list in app.routes.ts:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { About } from './about';
import { Home } from './home';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'about', component: About },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/">Home</a>
    <a routerLink="/about">About</a>
    <router-outlet />
  `,
})
export class App {}

Click Add one three times. The page shows:

HomeAbout
Count: 3
Add one

(The two links sit on one line, so the page text runs them together as HomeAbout.)

Before you read on, guess. Click About, then Home. What does the counter say?

Clicking About changes the address bar to /about, and the page shows:

HomeAbout
This app counts things.

Click Home. The address bar says / again, and the page shows:

HomeAbout
Count: 0
Add one

The count went back to 0. Leaving the home page destroyed the Home component, and its signal went with it. Coming back made a new Home, with a new signal that starts at 0. We’ll see one way to keep state across pages near the end of this part.

Three pieces made that work.

The routes. Routes is a list of route objects. Each one has a path and the component to show for it. The path has no leading slash: 'about' matches the URL /about. The empty path '' matches /, the home page. The router reads the list from top to bottom and uses the first route that matches.

The outlet. <router-outlet /> marks where the page goes. When the URL changes, the router destroys the old page’s component and creates the new one. It doesn’t put the page inside the outlet. It puts it right after it, as the next element. On the home page, the HTML inside <app-root> includes this:

<router-outlet></router-outlet><app-home>...</app-home>

So a CSS rule for router-outlet > * matches nothing. Style the page component itself.

The links. routerLink="/about" on an <a> turns it into a router link. It still gets a real href="/about", so the browser shows the address on hover, and “Open in new tab” works. But a normal click doesn’t load a new page. The router catches it, swaps the component and updates the address bar.

RouterLink and RouterOutlet are directives from @angular/router, so the component lists them in imports, like the directives in Part 11.

There’s a fourth piece you didn’t write. ng new already set up the router in src/app/app.config.ts:

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes)],
};

provideRouter(routes) gives the app a router that uses our list. It’s a provider, like the ones in Part 14, and it’s why app.routes.ts exists at all. (Your file may have the providers on separate lines. That’s the same code, formatted differently.) Later in this part we give provideRouter a second argument.

Here’s what a plain link does instead. This App keeps a Like counter outside the outlet, so it’s on every page. It has a router link and a plain href link to the same page. Keep the other files from the first example:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/about">About</a>
    <a href="/about">About (href)</a>
    <p><button (click)="likes.update((n) => n + 1)">Like</button> Likes: {{ likes() }}</p>
    <router-outlet />
  `,
})
export class App {
  protected readonly likes = signal(0);
}

Click Like twice, then About. The page shows:

AboutAbout (href)
Like Likes: 2
This app counts things.

Now click About (href). The page shows:

AboutAbout (href)
Like Likes: 0
This app counts things.

The plain link asked the server for /about. The browser threw the whole app away, loaded it again and started it from scratch, so every signal started over. ng serve answers any page address with index.html, which is why the app came back on the right page. A real web server must be set up to do the same, or reloading /about on your live site gives a 404. The router link only swapped one component. Inside your app, use routerLink.

A page for unknown URLs

What happens at an address no route matches? Keep the routes from the first example and add a Contact link with no route for it:

// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/">Home</a>
    <a routerLink="/about">About</a>
    <a routerLink="/contact">Contact</a>
    <router-outlet />
  `,
})
export class App {}

Click Contact. Nothing seems to happen. The address bar stays on /, and the page still shows the counter:

HomeAboutContact
Count: 0
Add one

The console says why:

ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: 'contact'

The router went through the list, found no route for contact, and stopped the navigation with an error. The router changes the address bar only when a navigation succeeds, so it still says /. Type localhost:4200/contact into the address bar instead, and you get the same error, an empty space where the page should be, and the address bar jumps back to /.

The fix is a wildcard route. The path '**' matches any URL. The router takes the first match, so it goes last:

// src/app/not-found.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-not-found',
  template: `<p>Page not found.</p>`,
})
export class NotFound {}
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { About } from './about';
import { Home } from './home';
import { NotFound } from './not-found';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'about', component: About },
  { path: '**', component: NotFound },
];

Click Contact now. The address bar shows /contact, and the page shows:

HomeAboutContact
Page not found.

The address stays as it was, which is what you want on a “not found” page: the reader can see their typo.

routerLinkActive: marking the current page

A menu usually shows which page you’re on. routerLinkActive="active" adds the CSS class active to a link while its route is the current one, and takes it away when it isn’t. Keep the files from the last example and change App:

// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterLinkActive, RouterOutlet],
  template: `
    <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>
    <a routerLink="/about" routerLinkActive="active" ariaCurrentWhenActive="page">About</a>
    <router-outlet />
  `,
  styles: `
    .active {
      font-weight: bold;
    }
  `,
})
export class App {}

Click About. The About link is now bold. Here’s its HTML, as the Elements tab of your browser’s developer tools shows it:

<a routerlink="/about" routerlinkactive="active" ariacurrentwhenactive="page" href="/about" class="active" aria-current="page">About</a>

Two things were added: class="active" and aria-current="page". The second comes from ariaCurrentWhenActive="page". A screen reader announces it as the current page, so people who can’t see the bold text still know where they are. Put it on every menu link. We left it off Home only to keep that line short.

Why { exact: true } on Home? By default, a link is active when the current URL begins with all of the link’s path segments. Home‘s path / has no segments, so it’s part of every URL, and without exact the Home link would be bold on every page. exact: true makes it active only at / itself. Exercise 1 shows the mistake.

Route parameters, read as inputs

A user directory has one page per user: /users/1, /users/2 and so on. You don’t write one route per user. You write one route with a parameter, a path segment that starts with a colon:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { UserPage } from './user-page';

export const routes: Routes = [{ path: 'users/:id', component: UserPage }];

users/:id matches /users/1, /users/42 or /users/ana, and calls the second segment id. The page needs to read it. In Angular 22 the simplest way is an input with the same name, like the inputs in Part 5:

// src/app/user-page.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-user-page',
  template: `<p>User {{ id() }}</p>`,
})
export class UserPage {
  readonly id = input.required<string>();

  constructor() {
    console.log('UserPage created');
  }
}

Nobody writes <app-user-page [id]="..."> anywhere. The router sets the input, but only once you turn that on. This is the second argument to provideRouter. Change app.config.ts:

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding()),
  ],
};

withComponentInputBinding() tells the router to copy route parameters, query parameters and route data into inputs with matching names. Functions named with... are router features: optional extras you pass to provideRouter after the routes.

Now the links. A link to a fixed address can be a plain string. When part of the address comes from data, bind [routerLink] to a list of segments, and the router joins them with slashes:

// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/users/1">Ana</a>
    <a [routerLink]="['/users', 2]">Ben</a>
    <router-outlet />
  `,
})
export class App {}

['/users', 2] becomes /users/2. Type localhost:4200/users/42 into the address bar. The page shows:

AnaBen
User 42

Click Ana, then Ben. The address bar says /users/2, and the page shows:

AnaBen
User 2

Press the browser’s Back button. The address bar says /users/1, and the page shows:

AnaBen
User 1

The router keeps the browser’s history, so Back and Forward work as on any site. Now look at the console. After three users, it has one line:

UserPage created

When only the parameter changes, the router keeps the same UserPage and sets its input again. That’s why it matters that the parameter is a signal: anything that reads id(), in the template or in a computed, updates when it changes. If you copied it into a plain field once, the page would keep showing the first user.

A parameter is always a string, because it’s a piece of the URL. id() above is '42', not 42. For a number, use the numberAttribute transform from Part 5: input.required({ transform: numberAttribute }). The worked example below does that.

Query parameters bind the same way. With /search?q=cat, an input named q gets 'cat'. Exercise 3 uses one.

Loading a page only when it’s visited

Every component that app.routes.ts imports is part of the app’s first download. In a big app that’s a lot of code for pages the user may never open. A route can instead name a function that loads its component the first time someone visits it. Back to Home and About, with About loaded that way:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'about', loadComponent: () => import('./about').then((m) => m.About) },
];

import('./about') with brackets is JavaScript’s dynamic import. It loads a file when that line runs, not when the app starts, and gives back a promise of the file’s exports. .then((m) => m.About) picks out the About class. loadComponent is the route option that takes such a function. Notice that there’s no import { About } at the top of app.routes.ts any more. If a file that’s itself in the first download, such as app.ts or a page that app.routes.ts imports, imports About the normal way, About is back in the first download too.

The build sees the dynamic import and puts about.ts in a file of its own, a lazy chunk. Here’s part of what ng build printed for this app (your file names and sizes will differ):

Initial chunk files | Names         |  Raw size | Estimated transfer size
chunk-XJYR2VSE.js   | -             | 111.88 kB |                33.84 kB
main-3HUWDTNK.js    | main          |  95.39 kB |                24.07 kB
...
Lazy chunk files    | Names         |  Raw size | Estimated transfer size
chunk-KKYT273M.js   | about         | 308 bytes |               308 bytes

To see when the chunk loads, put a console.log at the top of about.ts, outside the class. Code there runs once, when the file is loaded:

// src/app/about.ts
import { Component } from '@angular/core';

console.log('about.ts loaded');

@Component({
  selector: 'app-about',
  template: `<p>This app counts things.</p>`,
})
export class About {}
// src/app/home.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `<p>Welcome.</p>`,
})
export class Home {}
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/">Home</a>
    <a routerLink="/about">About</a>
    <router-outlet />
  `,
})
export class App {}

When the page loads, the console is empty:

Click About, Home, then About again. The console shows one line:

about.ts loaded

The file loaded on the first visit to /about, and the second visit reused it. The About component was still created again on each visit. Lazy loading changes when the code arrives, not how long the component lives. In the Network tab of your developer tools you can watch the chunk’s request appear on that first click.

Here’s that first click, step by step:

address bar routes, checked from the top / /about '' → Home 'about' → loadComponent '**' → NotFound no match not loaded loaded about chunk App component Home About <router-outlet /> Home: Welcome. About: This app counts things. URL /, Home on screen, about chunk not loaded Navigation to /about starts; the URL still says / '' doesn't match about; 'about' does About's code has arrived; the screen hasn't changed yet URL /about, About on screen The app is on /, and the outlet shows Home Click About: the router starts a navigation to /about The router checks the routes in order and stops at 'about' loadComponent runs, and the browser downloads the about chunk The router updates the URL and swaps Home for About

The URL picks a route. A lazy route loads its code first, then the router shows the page after the outlet.

Here are those steps in words, in case the animation doesn’t play for you:

  1. The app is at /. The empty-path route matched, so Home sits after the outlet. The about chunk hasn’t been downloaded.
  2. You click About. The router link stops the browser from loading a new page and asks the router to go to /about. The address bar and the screen don’t change yet.
  3. The router checks the routes from the top. '' doesn’t match about. 'about' does, so the router stops there and never looks at '**'.
  4. The about route has loadComponent, so the router calls it. The browser downloads the chunk, and the promise gives back the About class. On a later visit this step is skipped, because the chunk is already loaded.
  5. The router changes the address bar to /about, then destroys Home and creates About right after <router-outlet>. The page shows “This app counts things.”

A route with its own providers

In Part 14 we met two kinds of injectors: environment injectors for app-wide things, and element injectors for components. A route can add an environment injector of its own. List services in the route’s providers, and the router makes an injector for that route, between the root injector and the components the route shows.

Here’s a cart store that belongs to the shop page. It’s marked autoProvided: false, as in Part 13, so it exists only where it’s listed:

// src/app/cart-store.ts
import { Service, signal } from '@angular/core';

@Service({ autoProvided: false })
export class CartStore {
  readonly count = signal(0);

  constructor() {
    console.log('CartStore created');
  }
}
// src/app/shop.ts
import { Component, inject } from '@angular/core';
import { CartStore } from './cart-store';

@Component({
  selector: 'app-shop',
  template: `
    <p>Cart: {{ cart.count() }}</p>
    <button (click)="cart.count.update((n) => n + 1)">Add to cart</button>
  `,
})
export class Shop {
  protected readonly cart = inject(CartStore);
}

The route lists the store in providers:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { CartStore } from './cart-store';
import { Home } from './home';

export const routes: Routes = [
  { path: '', component: Home },
  {
    path: 'shop',
    loadComponent: () => import('./shop').then((m) => m.Shop),
    providers: [CartStore],
  },
];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/">Home</a>
    <a routerLink="/shop">Shop</a>
    <router-outlet />
  `,
})
export class App {}

home.ts is the Welcome one from the last example. Click Shop, Add to cart twice, then Home, then Shop again. The page shows:

HomeShop
Cart: 2
Add to cart

and the console has one line:

CartStore created

Compare that with the counter in “Try this first”, which went back to 0. Shop was destroyed and created again, just as Home was. But the cart lives in the route’s injector, not in the component. The router made that injector on the first visit to /shop and kept it, so the second Shop got the same store. By default the router keeps a route’s injector for as long as the app runs. (A router feature, withAutoCleanupInjectors(), can destroy unused ones; we won’t need it.)

Why not use @Service() and an app-wide store? Only the shop route can inject it, and each visit to the shop finds the same store. A component on another route that asks for CartStore gets error NG0201, as in Part 13. (Its code is still in the first download, because app.routes.ts imports it. Keeping it in a lazy chunk needs loadChildren, which Part 17 mentions.)

Worked example: a user directory

A small team directory: a list of people, a page per person, and a not-found page. The detail page loads lazily, and its id is a number. First the data, a plain list in its own file:

// src/app/users.ts
export interface User {
  id: number;
  name: string;
  role: string;
}

export const USERS: User[] = [
  { id: 1, name: 'Ana', role: 'Designer' },
  { id: 2, name: 'Ben', role: 'Developer' },
  { id: 3, name: 'Chloe', role: 'Tester' },
];

The list page links to each person:

// src/app/user-list.ts
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';
import { USERS } from './users';

@Component({
  selector: 'app-user-list',
  imports: [RouterLink],
  template: `
    <ul>
      @for (user of users; track user.id) {
        <li>
          <a [routerLink]="['/users', user.id]">{{ user.name }}</a>
        </li>
      }
    </ul>
  `,
})
export class UserList {
  protected readonly users = USERS;
}

users is a plain field, not a signal, because the list never changes. The detail page reads the id as a number and finds the person:

// src/app/user-detail.ts
import { Component, computed, input, numberAttribute } from '@angular/core';
import { RouterLink } from '@angular/router';
import { USERS } from './users';

@Component({
  selector: 'app-user-detail',
  imports: [RouterLink],
  template: `
    @if (user(); as u) {
      <h2>{{ u.name }}</h2>
      <p>Role: {{ u.role }}</p>
    } @else {
      <p>No user with id {{ id() }}.</p>
    }
    <a routerLink="/">All users</a>
  `,
})
export class UserDetail {
  readonly id = input.required({ transform: numberAttribute });
  protected readonly user = computed(() => USERS.find((u) => u.id === this.id()));
}
// src/app/not-found.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-not-found',
  template: `<p>Page not found.</p>`,
})
export class NotFound {}
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { NotFound } from './not-found';
import { UserList } from './user-list';

export const routes: Routes = [
  { path: '', component: UserList },
  { path: 'users/:id', loadComponent: () => import('./user-detail').then((m) => m.UserDetail) },
  { path: '**', component: NotFound },
];
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding()),
  ],
};
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  template: `
    <h1>Team</h1>
    <router-outlet />
  `,
})
export class App {}

App has no links of its own now, so it imports only RouterOutlet. The links live in the pages that show them, and each page imports RouterLink itself. The page shows:

Team
Ana
Ben
Chloe

Click Ben. The address bar says /users/2, and the page shows:

Team
Ben
Role: Developer
All users

Some things to notice:

  • input.required({ transform: numberAttribute }) turns '2' into the number 2 before the input stores it. TypeScript works out from the transform that id() is a number, so u.id === this.id() compares two numbers. Without the transform, id() would be a string, and the build would stop with TS2367, because a number and a string can never be equal.
  • user is a computed. When the router reuses this page for another id, user follows.
  • The All users link is part of the detail page, so it disappears with it.

Click All users, then press Back. You’re on Ben’s page again:

Team
Ben
Role: Developer
All users

Now try addresses that don’t fit. Type localhost:4200/users/9:

Team
No user with id 9.
All users

users/:id matched, because the route only checks the shape of the URL. It doesn’t know which ids exist. The page has to handle “no such user” itself, which is what the @else is for. Now type localhost:4200/users/abc:

Team
No user with id NaN.
All users

numberAttribute turned 'abc' into NaN, JavaScript’s “not a number” value. The page still worked, but says so in a strange way. In Part 17‘s exercises, a guard sends a URL like this, with an id that isn’t a number, to a not-found page instead. Finally, localhost:4200/teams:

Team
Page not found.

No route but the wildcard matches teams, so NotFound shows.

Worked example: reading NG0950

Here’s a mistake you’ll make once. Start from the team directory and put back the app.config.ts that ng new wrote, without withComponentInputBinding():

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes)],
};

It builds without a warning. Click Ben. The address bar changes to /users/2, but the page shows only:

Team
All users

and the console shows:

ERROR RuntimeError: NG0950: Input "id" is required but no value is available yet. Find more at https://v22.angular.dev/errors/NG0950

Read it piece by piece:

  • RuntimeError means it happened while the app was running, not while it was being built. The compiler can’t know that the router is meant to set id. Nothing in any template sets it, and for a routed component that’s normal.
  • NG0950 is Angular’s code. The link at the end explains it on angular.dev.
  • Input "id" is required but no value is available yet names the input. UserDetail was created and its template ran. The @if called user(), which called id(), and nothing had set id. A required input has no default, so reading it before it’s set is an error. Angular had already created the rest of the template, so the words All users appear. But the error stopped it before it finished: the link has no href, and clicking it does nothing.

So who should have set id? The router, and it only does that with withComponentInputBinding(). Put the config from the worked example back, and Ben works again. (An input that isn’t required gives no error at all in this situation. It just stays undefined, which is harder to spot.)

There’s a quieter version of the same problem. Here the config is right, but the route calls its parameter userId while the input is called id:

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding()),
  ],
};
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { NotFound } from './not-found';
import { UserList } from './user-list';

export const routes: Routes = [
  { path: '', component: UserList },
  { path: 'users/:userId', loadComponent: () => import('./user-detail').then((m) => m.UserDetail) },
  { path: '**', component: NotFound },
];

Click Ben. There’s no error at all, and the page shows:

Team
No user with id NaN.
All users

The router found no route value called id. By default, for an input with no matching value, it sets the input to undefined, so a value from an earlier page can’t linger. numberAttribute turned undefined into NaN. The fix is to use the same name in both places: users/:id and id = input.... Put the worked example’s routes back:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { NotFound } from './not-found';
import { UserList } from './user-list';

export const routes: Routes = [
  { path: '', component: UserList },
  { path: 'users/:id', loadComponent: () => import('./user-detail').then((m) => m.UserDetail) },
  { path: '**', component: NotFound },
];

Click Ben, and the page shows Ben again:

Team
Ben
Role: Developer
All users

When a routed page shows nothing, undefined or NaN, check two things: is withComponentInputBinding() in provideRouter, and does the parameter name in the path match the input name exactly?

In older code

Apps built with NgModules set up the router with RouterModule.forRoot(routes) in the imports of their root module, and RouterModule.forChild(routes) in feature modules. provideRouter(routes) replaces both. Lazy loading was done a module at a time: loadChildren: () => import('./admin/admin.module').then((m) => m.AdminModule). loadChildren still exists, and in current code it loads a list of routes instead. Part 17 covers child routes.

Before withComponentInputBinding(), a page read its parameters from the ActivatedRoute service: inject(ActivatedRoute), or a constructor parameter of that type. You’ll see this.route.snapshot.paramMap.get('id'), which reads the value once, and this.route.paramMap.subscribe(...), which follows changes. The snapshot version misses changes: when the router reuses the page for another id, as it did with UserPage, code that read the snapshot once doesn’t run again. ActivatedRoute isn’t deprecated and still has uses, but for reading a parameter, an input is shorter and always current. subscribe is RxJS, which Part 20 introduces.

Best practices

  • Use routerLink for every link inside the app. The app keeps its state and only the page changes. It replaces href, which reloads everything.
  • Read route and query parameters as inputs, with withComponentInputBinding(). The input is a signal, so the page follows when the router reuses it. It replaces reading ActivatedRoute by hand.
  • End every route list with a '**' route to a not-found page. Readers see a message instead of a blank space, and the console stays clean. It replaces NG04002 errors for every typo in a URL.
  • Lazy-load pages that aren’t on the first screen with loadComponent. The first download gets smaller, and each page arrives when it’s needed. It replaces importing every page into app.routes.ts.
  • Mark the current link with routerLinkActive and ariaCurrentWhenActive="page", and use exact: true on the / link. Everyone can see, or hear, where they are. It replaces hand-written [class.active] checks against the URL.
  • Put state that belongs to one section of the app in that route’s providers. It lives as long as the app, but only that route can inject it. It replaces app-wide services that only one page uses.

Tips and traps

  • A leading slash in a path. path: '/team' builds, but the app starts with NG04014: Invalid configuration of route '/team': path cannot start with a slash in the console, and no page shows. Paths in Routes never start with /; links usually do.
  • Forgetting RouterLink in imports. <a routerLink="/about"> builds without a word, because Angular treats routerLink as an ordinary attribute. The <a> gets no href, so it isn’t a link and clicking it does nothing. Add RouterLink to the component’s imports.
  • The wildcard route above other routes. Every URL shows “Page not found”, because the router takes the first match. Keep '**' last. Exercise 2 shows it.
  • Expecting a page’s signals to survive navigation. Leaving a page destroys its component, as the counter in “Try this first” showed. Keep data that must survive in a service: app-wide, or in a route’s providers.
  • A default value for a query-parameter input. q = input('') looks safe, but when the URL has no q, the router by default sets the input to undefined, not ''. Declare it as input<string>(), which allows undefined, and handle that case.
  • Importing a lazy page somewhere else. If a file in the first download, such as app.ts, has import { About } from './about', the build moves About back into the first download. The build output still lists an about chunk, but it’s only a few bytes. Search for imports of a lazy page when its chunk looks too small.

The URL picks the route, the route picks the component, and the outlet shows it.

Exercises

Exercise 1. Add a menu to the team directory. Keep every other file from the worked example, and use this App. Open Ben’s page. Both links are bold. Why? Fix it.

// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterLinkActive, RouterOutlet],
  template: `
    <h1>Team</h1>
    <a routerLink="/" routerLinkActive="active">Home</a>
    <a routerLink="/users/2" routerLinkActive="active">Ben</a>
    <router-outlet />
  `,
  styles: `
    .active {
      font-weight: bold;
    }
  `,
})
export class App {}

Exercise 2. Someone tidies the team directory’s routes and moves the '**' route to the top of the list. Without running it, what does / show now? And /users/2?

Exercise 3. Write a search page at /search. At /search?q=cat it shows Results for: cat. At /search with no q, it shows Type something to search. Add a link Search for cat that goes to /search?q=cat. Hint: routerLink has a queryParams input that takes an object, such as { q: 'cat' }.

Answers

1. Without options, a link is active when the current URL begins with all of the link’s path segments. Home‘s path / has no segments, so it’s part of /users/2 too, and Home counts as active. Add [routerLinkActiveOptions]="{ exact: true }" to the Home link:

// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterLinkActive, RouterOutlet],
  template: `
    <h1>Team</h1>
    <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>
    <a routerLink="/users/2" routerLinkActive="active">Ben</a>
    <router-outlet />
  `,
  styles: `
    .active {
      font-weight: bold;
    }
  `,
})
export class App {}

On Ben’s page, only Ben has class="active" now.

2. Both show Page not found. The router tries the routes from the top, and '**' matches any URL, so it wins every time. Here’s the run, with the menu from Exercise 1:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { NotFound } from './not-found';
import { UserList } from './user-list';

export const routes: Routes = [
  { path: '**', component: NotFound },
  { path: '', component: UserList },
  { path: 'users/:id', loadComponent: () => import('./user-detail').then((m) => m.UserDetail) },
];
Team
HomeBen
Page not found.
Team
HomeBen
Page not found.

Move '**' back to the end, as in the worked example.

3. The query parameter q binds to an input named q, the same way a path parameter does. With no q in the URL the router sets the input to undefined, so declare it with input<string>(), which allows that, and test it with @if:

// src/app/search.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-search',
  template: `
    @if (q()) {
      <p>Results for: {{ q() }}</p>
    } @else {
      <p>Type something to search.</p>
    }
  `,
})
export class Search {
  readonly q = input<string>();
}
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { Search } from './search';

export const routes: Routes = [{ path: 'search', component: Search }];
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <a routerLink="/search" [queryParams]="{ q: 'cat' }">Search for cat</a>
    <router-outlet />
  `,
})
export class App {}

app.config.ts is the one with withComponentInputBinding(). Type localhost:4200/search. The page shows:

Search for cat
Type something to search.

Click Search for cat. The address bar says /search?q=cat, and the page shows:

Search for cat
Results for: cat

What’s next

Our routes so far let anyone go anywhere, and each page loads its data after it appears. In Part 17, we’ll add guards that decide whether a navigation may happen, resolvers that load data before a page shows, child routes, redirects and page titles.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.