Sub topic 9
Building Nested Layouts with Child Routes
This chapter assumes you know TypeScript, standalone components, inject(), and basic RxJS. It also assumes you have read the earlier chapters on provideRouter, RouterOutlet, RouterLink, and route parameters.
Most real applications have layouts inside layouts. A products section might have a sidebar that stays on screen while the main panel changes. Inside one product page, tabs such as "Overview" and "Reviews" might switch content while the product header stays put. Child routes let you describe that structure in the route table so the router can render it for you.
The working model
A child route is a route nested in the children array of another route. When the router matches a URL, it walks the route tree from the top. Each matched route takes one or more URL segments. A matched route that has a component renders that component into the nearest RouterOutlet above it.
These rules follow from that model:
- The top-level matched component renders into the root
<router-outlet />, usually inAppComponent. - A child's component renders into a
<router-outlet />inside the parent's template. - Child paths are relative to the parent path. A child with
path: 'reviews'under a parent withpath: 'products/:id'matches/products/42/reviews.
The router does not flatten the tree. Each level of the route tree gets its own outlet in the component tree, and the components stay alive while only the deeper levels change.
Defining the route tree
This route table has two levels of nesting. The products section has a layout with a list or a detail view, and the detail view has its own tabs.
// app.routes.ts
import { Routes } from '@angular/router';
import { ProductsLayoutComponent } from './products/products-layout.component';
import { ProductListComponent } from './products/product-list.component';
import { ProductDetailComponent } from './products/product-detail.component';
import { ProductOverviewComponent } from './products/product-overview.component';
import { ProductReviewsComponent } from './products/product-reviews.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', redirectTo: 'products', pathMatch: 'full' },
{
path: 'products',
component: ProductsLayoutComponent,
children: [
{ path: '', component: ProductListComponent, title: 'Products' },
{
path: ':id',
component: ProductDetailComponent,
children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'overview', component: ProductOverviewComponent },
{ path: 'reviews', component: ProductReviewsComponent }
]
}
]
},
{ path: '**', component: NotFoundComponent }
];The router renders the following for some sample URLs:
| URL | Root outlet | Layout outlet | Detail outlet |
|---|---|---|---|
| `/products` | ProductsLayoutComponent | ProductListComponent | none |
| `/products/42` | redirected to `/products/42/overview` | ||
| `/products/42/overview` | ProductsLayoutComponent | ProductDetailComponent | ProductOverviewComponent |
| `/products/42/reviews` | ProductsLayoutComponent | ProductDetailComponent | ProductReviewsComponent |
| `/products/42/specs` | NotFoundComponent | none | none |
The empty-path child (path: '') is the default content for its parent. Without it, /products would render the layout with an empty outlet. The redirect under :id uses pathMatch: 'full'. Without that option, the empty path would match the start of every URL and the redirect would fire for reviews too.
The last row has a subtle point. /products/42/specs does not match any child of :id. The router then backtracks and tries the next top-level routes, and the wildcard catches the URL. The whole page becomes the not-found page, including the sidebar. If you want a not-found message inside the layout, add a { path: '**', component: ... } as the last child of products.
Parent components need their own outlet
A parent component must place a <router-outlet /> where its children should appear. Forgetting this is the most common child-route bug. The URL changes and no errors are logged, but nothing shows up.
// products/products-layout.component.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-products-layout',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<aside>
<a routerLink="/products"
routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }">All products</a>
<a routerLink="/products/1" routerLinkActive="active">Product 1</a>
<a routerLink="/products/2" routerLinkActive="active">Product 2</a>
</aside>
<main>
<router-outlet />
</main>
`
})
export class ProductsLayoutComponent {}The exact: true option matters here. By default routerLinkActive treats a link as active when the current URL starts with the link's URL. So without that option, "All products" would stay highlighted on every product page.
Relative links and the tab component
The detail component shows a header and tab links, and it has an outlet for the tab content:
// products/product-detail.component.ts
import { Component, Input, inject } from '@angular/core';
import { ActivatedRoute, Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-product-detail',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<h2>Product {{ id }}</h2>
<nav>
<a routerLink="overview" routerLinkActive="active">Overview</a>
<a routerLink="reviews" routerLinkActive="active">Reviews</a>
<a routerLink="..">Back to list</a>
</nav>
<router-outlet />
<button (click)="openReviews()">Read reviews</button>
`
})
export class ProductDetailComponent {
@Input() id!: string;
private router = inject(Router);
private route = inject(ActivatedRoute);
openReviews(): void {
this.router.navigate(['reviews'], { relativeTo: this.route });
}
}A routerLink value without a leading / is relative to the route of the component that contains the link. That is the :id route, so on /products/42, "overview" resolves to /products/42/overview and ".." resolves to /products. Relative links keep a section portable. You can move the whole subtree under a different prefix and the links still work.
Router.navigate does not work this way. It treats commands as absolute unless you pass relativeTo. If you leave out relativeTo, navigate(['reviews']) goes to /reviews, which the wildcard catches.
Reading parent parameters in a child
id binds to ProductDetailComponent because that component's own route declares :id. ProductReviewsComponent sits one level deeper on the reviews route, and by default it does not see id.
The router's default paramsInheritanceStrategy is 'emptyOnly'. Under that strategy, a child inherits its parent's params and data only when the child has an empty path or the parent has no component. The reviews route meets neither condition.
You can handle this in two ways. The first is to read the parent route directly:
// products/product-reviews.component.ts
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs';
@Component({
selector: 'app-product-reviews',
standalone: true,
imports: [AsyncPipe],
template: `<p>Reviews for product {{ productId$ | async }}</p>`
})
export class ProductReviewsComponent {
private route = inject(ActivatedRoute);
productId$ = this.route.parent!.paramMap.pipe(
map(params => params.get('id')!)
);
}Use the observable paramMap here and not snapshot. When the user goes from /products/1/reviews to /products/2/reviews, the router reuses both component instances. A snapshot read in the constructor would keep showing product 1.
The second way is to turn on inheritance for the whole app:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withComponentInputBinding, withRouterConfig } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withRouterConfig({ paramsInheritanceStrategy: 'always' })
)
]
});With 'always', a child can declare @Input() id!: string; and receive the parent's parameter. This is convenient, but it can cause name collisions. If a parent and a child both declare :id, the child's value wins and the parent's value is hidden. Choose one approach per project and use it consistently.
Componentless parent routes
A parent does not need a component. A route with children and no component groups routes under a shared prefix, guard, or resolver without adding a layout level:
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { ProfileComponent } from './account/profile.component';
import { BillingComponent } from './account/billing.component';
export const accountRoutes: Routes = [
{
path: 'account',
canActivateChild: [authGuard],
children: [
{ path: 'profile', component: ProfileComponent },
{ path: 'billing', component: BillingComponent }
]
}
];ProfileComponent renders directly into the outlet above account, because there is no account component to host an outlet. Children of a componentless parent also inherit its params and data under the default strategy. canActivateChild runs before each child activates, including when the user moves between siblings. The guards chapter covers guards in detail. Componentless parents are also where lazy-loaded route groups usually attach, which the next chapter covers.
Common errors at a glance
| Symptom | Likely cause |
|---|---|
| URL changes but the child area stays blank | The parent template has no `<router-outlet />`, or `RouterOutlet` is missing from `imports` |
| Parent URL shows an empty panel | No empty-path default child |
| Default redirect fires on every child URL | `redirectTo` on an empty path without `pathMatch: 'full'` |
| Child input is always `undefined` | The parameter belongs to the parent and inheritance is `'emptyOnly'` |
| `navigate(['x'])` lands on the not-found page | Missing `relativeTo: this.route` |
| Parent nav link stays highlighted on all children | `routerLinkActive` without `exact: true` |
Exercise
With the route table in this chapter, a user on /products/7/overview clicks a link with routerLink="../reviews" placed inside ProductOverviewComponent's template. Where do they end up, and why?
Show answer
/products/7/reviews. The link is relative to the overview route (/products/7/overview). ".." moves up to the :id route (/products/7), and "reviews" is then appended.
Exercise
You add { path: 'specs', component: ProductSpecsComponent } as a child of ':id', and ProductSpecsComponent declares @Input() id!: string. The app uses withComponentInputBinding() and default router config. What value does id have, and name two ways to fix it.
Show answer
It is undefined, because 'specs' has a non-empty path and its parent has a component, so the default 'emptyOnly' strategy does not pass down :id. Fix it by reading inject(ActivatedRoute).parent!.paramMap, or by adding withRouterConfig({ paramsInheritanceStrategy: 'always' }) to provideRouter.
Exercise
Why does /products/42/specs show the full-page NotFoundComponent with no sidebar, and how would you show a not-found message inside the products layout instead?
Show answer
No child of products or :id matches 'specs', so the router backtracks to the top-level routes, and the root wildcard renders into the root outlet in place of the layout. Add { path: '**', component: ProductNotFoundComponent } as the last child of the products route (or of :id) so the router matches it inside the layout's outlet.