tezvyn:

Nested Routes: Mapping URLs to Component Trees

AI-drafted, machine-checkedSource: angular.devintermediate
Nested Routes: Mapping URLs to Component Trees

Nested routes map URL segments to components inside other components, like a sub-page within a main layout. This is common for user dashboards with sections like 'profile' and 'settings'. The footgun is forgetting the child router outlet.

WHY IT EXISTS: Modern apps often have complex layouts where one part of the UI changes while another stays the same, like a sidebar and a main content area. Nested routes were created to manage this relationship between URL structure and component hierarchy cleanly.

THE MENTAL MODEL: Think of nested routes like Russian nesting dolls for your UI. The outermost doll is your main app layout. A URL like /users might show a user list. A URL like /users/jane/profile opens the user component doll to reveal a profile component inside it, while the rest of the user component (like a user-specific sidebar) remains visible.

HOW IT WORKS: You define routes in a hierarchical structure. A top-level route, like /users, maps to a parent component. This parent component contains a special placeholder (like <router-outlet> in Angular or <RouterView> in Vue). Child routes, like :id/profile, are defined as children of the parent. When a child route is active, its component is rendered in the parent's placeholder, while the parent component itself remains.

WHEN TO USE IT: Use this for master-detail interfaces (a list and a detail view), tabbed interfaces on one page, and dashboards with sub-sections like Profile, Settings, and Billing. It's ideal anytime you have a consistent layout wrapper around changing content views.

WHEN NOT TO USE IT: For simple, flat applications with only top-level pages, nesting is overkill. If two views share no common UI layout or data, they should be sibling routes, not parent-child. Don't force a nested structure if a shared service can manage state between independent pages.

ONE CANONICAL EXAMPLE: In an app, the /settings route shows a SettingsComponent with links for 'Profile' and 'Account'. This component has a <router-outlet>. Clicking 'Profile' navigates to /settings/profile, which renders the ProfileComponent inside the SettingsComponent's outlet, leaving the main settings navigation visible.

Read the original → angular.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.