Sub topic 1
How Client-Side Routing Works in Angular
Prerequisites
This chapter assumes you know TypeScript, Angular standalone components and templates, the inject() function, dependency injection with services, and basic RxJS Observables.
The Routing Model
In a single-page application (SPA), the browser loads one HTML page. After that, the Angular Router watches the URL. When the URL changes, the router matches it against a list of routes and swaps the matching component into the page. No full page reload happens. The router uses the browser History API, so the back and forward buttons keep working.
Defining Routes and Registering the Router
A route is an object that pairs a path with a component. The router checks routes in order and uses the first one that matches, so put specific paths before general ones.
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { ProductDetailComponent } from './product-detail.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent, title: 'Home' },
{ path: 'products/:id', component: ProductDetailComponent }
];
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app.component';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)]
});Paths do not start with a slash. The title property sets the browser tab title when that route is active.
Rendering with RouterOutlet and Navigating with RouterLink
RouterOutlet marks the spot where the matched component appears. RouterLink turns an anchor into an in-app link that does not reload the page. RouterLinkActive adds a CSS class while the link's route is active.
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<nav>
<a routerLink="/home" routerLinkActive="active">Home</a>
<a [routerLink]="['/products', 42]" routerLinkActive="active">Product 42</a>
</nav>
<router-outlet />
`
})
export class AppComponent {}The array form ['/products', 42] builds the URL /products/42 from parts.
Exercise
You add { path: 'products/:id', ... } before { path: 'products/new', ... }. What happens when a user visits /products/new, and how do you fix it?
Show answer
The router uses the first match, so products/:id matches with id set to "new". Move products/new above products/:id.