What Is Routing?
In a single page app the browser never loads a new HTML page, but the URL still changes. The router shows the right component for each URL, so users can bookmark pages and use the back button.
Step 1: Define Routes
typescript
// app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home/home';
import { About } from './about/about';
import { NotFound } from './not-found/not-found';
export const routes: Routes = [
{ path: '', component: Home, title: 'Home' },
{ path: 'about', component: About, title: 'About us' },
{ path: 'products', redirectTo: 'shop', pathMatch: 'full' },
{ path: '**', component: NotFound, title: 'Page not found' }, // always last
];
typescript
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};
Step 2: router-outlet and Menu
typescript
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 /> <!-- the matched component appears here -->
</main>
`,
styles: `a.active { font-weight: bold; color: #0d6efd; }`,
})
export class App {}
| Piece | Purpose |
Routes | List of URL to component mappings |
<router-outlet /> | Placeholder where the page component renders |
routerLink | A link that does not reload the page (never use href for internal links) |
routerLinkActive | Adds a CSS class to the current link |
title | Sets the browser tab title for the route |
Order matters: The router uses the first matching route. Put specific routes first and the wildcard ** last.
Navigate from Code
typescript
export class LoginForm {
private router = inject(Router);
onLoggedIn() {
this.router.navigate(['/dashboard']);
// with parameters
this.router.navigate(['/products', 42]);
// with query params
this.router.navigate(['/search'], { queryParams: { q: 'angular', page: 1 } });
// by URL text
this.router.navigateByUrl('/about');
}
}
Links with Parameters
html
<a [routerLink]="['/products', product.id]">{{ product.name }}</a>
<a routerLink="/search" [queryParams]="{ q: 'angular' }">Search</a>
Not Found and Server Setup
When someone opens /about directly, the server must serve index.html for every path. ng serve does this for you. On your own server (Nginx, Apache) you must add a fallback rule (see the deployment lesson).
Default title strategy: You can create one title for the whole app by providing a custom TitleStrategy that adds a suffix such as " | My Shop".
Conclusion
Declare Routes, register them with provideRouter, show pages in <router-outlet /> and link with routerLink. Use Router.navigate for navigation from code.
Quick Summary: routes + provideRouter + router-outlet + routerLink.