Sub topic 14
Adding Pages with the Router
So far your app has a single screen: the root component and whatever it renders. Real applications have several pages, such as a home page, an about page, and a detail view for each product. Angular's router lets you map URLs to components. It swaps the visible component when the URL changes, and the browser never does a full page reload. This chapter covers how routes are declared, registered, rendered and navigated, plus the mistakes that come up most often.
This chapter assumes you have worked through the earlier chapters on bootstrapping (main.ts and app.config.ts), standalone components, templates and binding, and signal inputs.
The Working Model
Client-side routing is a loop with four parts:
- A route table (
Routes) is an ordered array of objects, each pairing a URL path with a component. provideRouter(routes)registers the router service and your table with the application injector inapp.config.ts.- A
<router-outlet>in a template marks where the matched component is rendered. - Navigation happens through
routerLinkin templates orRouter.navigate()in code. It updates the URL with the History API, and the router then matches the new URL against the table.
Declaring and Registering Routes
Start by generating two page components:
ng generate component home
ng generate component aboutRecent CLI versions create src/app/home/home.ts with a class named Home. Older versions create home.component.ts with HomeComponent. Adjust the imports below to match what your CLI produced.
Recent ng new projects already contain app.routes.ts and wire it into app.config.ts. If yours does not, create both:
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home/home';
import { About } from './about/about';
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'about', component: About },
{ path: '**', redirectTo: '' },
];// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};Here is what each route does:
| Route | Matches | Notes |
|---|---|---|
| `''` | `/` | The empty path is the default page |
| `'about'` | `/about` | Paths never start with `/` |
| `'**'` | anything else | Wildcard. It must be last, because matching stops at the first hit |
Rendering Routes with RouterOutlet and RouterLink
The root component needs an outlet and some links. In a standalone component, every directive used in the template must be listed in imports:
// src/app/app.ts
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<nav>
<a routerLink="/" routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
</nav>
<main>
<router-outlet />
</main>
`,
styles: `.active { font-weight: bold; }`,
})
export class App {}routerLink intercepts the click and navigates inside the app. routerLinkActive adds a CSS class while its link's route is active. The exact: true option stops the Home link from staying highlighted on every page, since every URL starts with /.
The routed component is rendered as a sibling right after <router-outlet>, not inside it. Keep this in mind when you write CSS selectors.
Route Parameters
Detail pages need a variable segment in the URL. A colon declares a parameter:
{ path: 'products/:id', component: ProductDetail },The cleanest way to read the parameter is component input binding. Turn it on once in the config:
// src/app/app.config.ts
import { provideRouter, withComponentInputBinding } from '@angular/router';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding())],
};The router now passes the :id value to a signal input with the same name:
// src/app/product-detail/product-detail.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-product-detail',
template: `<h2>Product {{ id() }}</h2>`,
})
export class ProductDetail {
id = input.required<string>();
}Route parameters always arrive as strings. Convert them yourself if you need a number, for example with computed(() => Number(this.id())).
Without withComponentInputBinding(), you inject ActivatedRoute and read route.snapshot.paramMap.get('id'), or subscribe to route.paramMap. The difference matters when the user navigates from /products/1 to /products/2. Angular reuses the component instance when only parameters change, so a value read once from the snapshot goes stale. Signal inputs and the paramMap observable both update, and the snapshot does not.
To link to a parameterised route, pass an array:
<a [routerLink]="['/products', product.id]">{{ product.name }}</a>Navigating from Code
After a form submit or a login, you often need to navigate from code. Inject Router and call navigate:
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-search',
template: `<button (click)="open(42)">Open product 42</button>`,
})
export class Search {
private router = inject(Router);
open(id: number) {
this.router.navigate(['/products', id]);
}
}navigate returns a Promise<boolean>. It resolves to false if the navigation was cancelled, for example by a guard.
Lazy Loading Pages
With component:, every page is bundled into the initial download. loadComponent moves a page into its own chunk, which the browser fetches only on the first visit to that route:
export const routes: Routes = [
{ path: '', component: Home },
{
path: 'about',
loadComponent: () => import('./about/about').then((m) => m.About),
},
{ path: '**', redirectTo: '' },
];Do not also import About statically at the top of app.routes.ts. A static import pulls the component back into the main bundle and cancels the benefit. Run ng build and the CLI's output lists the lazy chunks separately, so you can confirm the split worked.
| Approach | Initial bundle | First visit to page | Good for |
|---|---|---|---|
| `component:` | Larger | Instant | Home page and small apps |
| `loadComponent:` | Smaller | Short fetch delay | Secondary or heavy pages |
Redirects and pathMatch
A redirect from the empty path needs pathMatch: 'full':
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: Home },The default pathMatch is 'prefix', and every URL has the empty string as a prefix. Without 'full', every URL would redirect, and Angular rejects this configuration with an error. The '**' wildcard does not have this problem.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `'router-outlet' is not a known element` | `RouterOutlet` is missing from `imports` | Add it to the component's `imports` |
| Link does nothing and has no `href` | `RouterLink` is not imported | Import `RouterLink` |
| Error about an invalid path | The path starts with `/` | Use `'about'`, not `'/about'` |
| Every URL shows the home page | The `'**'` route is placed before other routes | Move the wildcard to the end |
| Detail page shows the old ID | The component was reused and the value was read from the snapshot | Use input binding or `paramMap` |
| Deep links return 404 in production | The server does not fall back to `index.html` | Configure the server to rewrite unknown paths to `index.html` |
The last row needs some explanation. ng serve already serves index.html for unknown paths, so deep links work during development. A static host such as S3, Nginx or GitHub Pages looks for a real file at /about and returns 404. You must configure the host to return index.html for unknown paths.
Exercise
Your route table is [{ path: '**', component: NotFound }, { path: 'about', component: About }]. Visiting /about shows NotFound. Why, and what is the fix?
Show answer
The router checks routes in array order and stops at the first match. The '**' wildcard matches every URL, so it wins before 'about' is checked. Move the wildcard route to the end of the array.
Exercise
Add a lazily loaded route at /users/:userId that renders a UserProfile component and displays the ID. What two changes besides the route itself are needed for the component to receive userId through a signal input?
Show answer
Add { path: 'users/:userId', loadComponent: () => import('./user-profile/user-profile').then(m => m.UserProfile) } to the routes. Then enable withComponentInputBinding() in provideRouter in app.config.ts, and declare userId = input.required<string>() in UserProfile. The input name must match the parameter name exactly.
Exercise
A user goes from /products/1 to /products/2 by clicking a link on the detail page. The heading still says "Product 1". The component reads the ID in its constructor with route.snapshot.paramMap.get('id'). Explain the cause.
Show answer
Angular reuses the ProductDetail instance because only the parameter changed, so the constructor does not run again and the snapshot value stays stale. Read the ID through a signal input with withComponentInputBinding(), or subscribe to route.paramMap, so the value updates on each navigation.