Loading

Quipoin Menu

Learn • Practice • Grow

angular / Child Routes
tutorial

Child Routes

Imagine a user profile page with tabs: Overview, Posts, Settings. Each tab should show different content, but the header and sidebar remain the same. This is where child routes (nested routes) come in – they allow you to have components within components based on the URL.

Why Child Routes?
  • Share common layout (header, sidebar) across related pages.
  • Organize complex feature modules.
  • Cleaner URL structure like /user/123/posts, /user/123/settings.

Setting Up Child Routes
First, create a parent component that will contain the child routes:


@Component({
selector: 'app-user',
template: `
<h2>User Profile: {{ userId }}</h2>
<nav>
<a routerLink="overview" routerLinkActive="active">Overview</a> |
<a routerLink="posts" routerLinkActive="active">Posts</a> |
<a routerLink="settings" routerLinkActive="active">Settings</a>
</nav>
<router-outlet></router-outlet>
`

})
export class UserComponent {
userId: string;
constructor(private route: ActivatedRoute) {
this.userId = this.route.snapshot.paramMap.get('id');
}
}

Now define child routes using the children property:


const routes: Routes = [
{
path: 'user/:id',
component: UserComponent,
children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'overview', component: UserOverviewComponent },
{ path: 'posts', component: UserPostsComponent },
{ path: 'settings', component: UserSettingsComponent }
]
}
];

Now URLs work like this:
  • /user/123 – redirects to /user/123/overview
  • /user/123/overview – shows UserOverviewComponent inside UserComponent
  • /user/123/posts – shows UserPostsComponent inside UserComponent

Accessing Parent Route Data in Child
Sometimes a child component needs data from the parent route (like userId). You can access it via the parent route:


export class UserPostsComponent {
userId: string;

constructor(private route: ActivatedRoute) {
// Access parent route parameters
this.userId = this.route.parent.snapshot.paramMap.get('id');
}
}
Two Minute Drill
  • Child routes create nested navigation.
  • Parent component contains its own <router-outlet> for children.
  • Use children array in route configuration.
  • Access parent route data via `route.parent`.
  • Perfect for tabbed interfaces, profile sections, dashboards.

Need more clarification?

Drop us an email at career@quipoinfotech.com