Nested Routing Explained - Child Routes & Default Child Route
Nested routing means routing inside another route.
It is also called child routing.
There is no limit – routing can have multiple levels.
Example:
- Home
- User
- Profile
- Setting
What We Build
- Main routes: Home, User
- Inside User:
- Profile
- Setting
- Profile opens by default when User page loads
Create Components
ng g c pages/home
ng g c pages/user
ng g c pages/profile
ng g c pages/setting
App Routes (app.routes.ts)
import { Routes } from '@angular/router';
import { Home } from './pages/home/home';
import { User } from './pages/user/user';
import { Profile } from './pages/profile/profile';
import { Setting } from './pages/setting/setting';
export const routes: Routes = [
{ path: '', component: Home },
{
path: 'user',
component: User,
children: [
{ path: '', redirectTo: 'profile', pathMatch: 'full' },
{ path: 'profile', component: Profile },
{ path: 'setting', component: Setting }
]
}
];
children is used for nested routing
Blank path + redirectTo is used for default child route
App Component (app.ts)
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink],
templateUrl: './app.html'
})
export class App {}
App HTML (app.html)
<nav>
<a routerLink="">Home</a>
<a routerLink="user">User</a>
</nav>
<hr />
<router-outlet></router-outlet>
User Component (user.ts)
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink } from '@angular/router';
@Component({
selector: 'app-user',
standalone: true,
imports: [RouterOutlet, RouterLink],
templateUrl: './user.html'
})
export class User {}
User HTML (user.html)
<h2>User Page</h2>
<nav class="child-nav">
<a routerLink="profile">Profile</a>
<a routerLink="setting">Setting</a>
</nav>
<router-outlet></router-outlet>
Key Points
- Nested routing = routing inside routing
childrenis used for child routes- Child routes need router-outlet inside parent component
- Default child route uses:
path: ''redirectTopathMatch: 'full'- Redirect must be inside
children, not outside