Course Content
ANGULAR Tutorial
About Lesson

Nested routes and child routes

Routing in Angular isn’t just about navigating between different pages. It’s also about structuring and organizing your application’s views. Nested routes and child routes play a pivotal role in this, offering a way to manage complex UI hierarchies efficiently.

What are Nested Routes?

Nested routes refer to routing configurations within other routing configurations. In Angular, this involves defining routes within the routes of a feature module or a parent route. These nested routes allow for the creation of more intricate and organized user interfaces.

How do Child Routes Work?

Child routes are a subset of nested routes and are configured within a parent component’s route configuration. They allow for a more granular control of the UI and navigation within a specific section or component.

Implementation in Angular:

  1. Defining Nested Routes:

    • In your routing module, configure routes as children within the parent route’s configuration.
    • Example:
     
    const routes: Routes = [
    {
    path: 'parent',
    component: ParentComponent,
    children: [
    { path: 'child', component: ChildComponent }
    ] }
    ];
  2. Navigating to Child Routes:

    • Use router links or programmatic navigation to access child routes.
    • Example:
     
    <!-- Router Link -->
    <a routerLink="/parent/child">Go to Child Route</a>

    <!-- Programmatic Navigation -->
    <button (click)="navigateToChild()">Navigate</button>

     
    // TypeScript
    navigateToChild() {
    this.router.navigate(['/parent/child']);
    }
    • Define a <router-outlet> in the parent component’s template where child components will be rendered.
    • Example:

      Outlet for Child Routes:

  3. <!-- Parent Component Template -->
    <h2>Parent Component</h2>
    <router-outlet></router-outlet>

Benefits of Nested and Child Routes:

  • Modular and Organized Structure: Nesting routes helps in organizing complex UI structures by breaking them into manageable components.

  • Granular Control: Child routes enable specific navigation and functionality within a particular section of the application.

  • Code Reusability: Encourages the reuse of components across various parts of the application, reducing redundancy