Routing in Angular is like the system of trails connecting the castles of feudal Japan. Each path leads to a different place, and the Router is the guide showing the way.
1// app.config.ts
2import { ApplicationConfig } from '@angular/core';
3import { provideRouter } from '@angular/router';
4import { routes } from './app.routes';
5
6export const appConfig: ApplicationConfig = {
7 providers: [
8 provideRouter(routes)
9 ]
10};1// app.routes.ts
2import { Routes } from '@angular/router';
3import { HomeComponent } from './home.component';
4import { NotFoundComponent } from './not-found.component';
5
6export const routes: Routes = [
7 // Default redirect
8 { path: '', redirectTo: '/home', pathMatch: 'full' },
9
10 // Static route
11 { path: 'home', component: HomeComponent },
12
13 // Route with parameter
14 { path: 'samurai/:id', component: SamuraiDetailComponent },
15
16 // Lazy loading a component
17 {
18 path: 'dojo',
19 loadComponent: () => import('./dojo/dojo.component')
20 .then(c => c.DojoComponent)
21 },
22
23 // Lazy loading routes
24 {
25 path: 'weapons',
26 loadChildren: () => import('./weapons/weapons.routes')
27 .then(r => r.WEAPONS_ROUTES)
28 },
29
30 // Wildcard - 404 handling
31 { path: '**', component: NotFoundComponent }
32];Router Outlet is where Angular renders components for the current route:
1@Component({
2 selector: 'app-root',
3 standalone: true,
4 imports: [RouterOutlet, RouterLink, RouterLinkActive],
5 template: \`
6 <nav class="navigation">
7 <a routerLink="/home"
8 routerLinkActive="active"
9 [routerLinkActiveOptions]="{ exact: true }">
10 🏠 Home
11 </a>
12 <a routerLink="/samurai" routerLinkActive="active">
13 ⚔️ Samurai
14 </a>
15 <a routerLink="/dojo" routerLinkActive="active">
16 🏯 Dojo
17 </a>
18 </nav>
19
20 <main>
21 <router-outlet></router-outlet>
22 </main>
23 \`
24})
25export class AppComponent { }| Type | Example URL | Usage | |------|-------------|-------| | Path params | /samurai/123 | Required, part of the path | | Query params | /samurai?sort=name | Optional, filtering | | Fragment | /samurai#section | Navigation to a section |