Angular Js

How to create Nested or Child routes in Angular?

How to create Nested or Child routes in Angular?

How to create Nested or Child routes in Angular?

This Article helps you to Understand, How to create Nested or Child routes in Angular?


Routes within other routes are known as nested routes. We'll demonstrate how to build a child route and display the child components in this tutorial. We can successfully create a tree of routes using Angular's ability to nest child routes under other child routes.


Sibling Routes
Here the  ServerComponent is defined as the sibling of the ServersComponent and not as the child

{ path: "servers", component: ServersComponent },
  { path: "servers/:id", component: ServerComponent },
{ path: "servers/:id/edit", component: EditServerComponent },


To make the ServerComponent as the child of the ServerComponent , we need to add the children key to the servers route, which is an array of all child routes

 
{
    path: "servers",   
    component: ServersComponent,
    children: [
      {
        path: ":id",
        component: ServerComponent,       
      },  
{
        path: ":id/edit",
        component: EditServerComponent,     
      } 
    ]
  },


The child route definition is similar to the parent route definition. It has a path and component that gets invoked when the user navigates to the child route.
In the above example, the parent route path is ‘servers’ and the child route is ‘id’ and "id/edit"
This is will match the URL path “/servers/1” or "/servers/1/edit"
When the user navigates to the “/servers/id”, the router will start to look for a match in the routes array


Display the component using Router-outlet
The components are always rendered in the <RouterOutlet> of the parent component.
For ServerComponent the parent component is ServersComponent and not the AppComponent
Hence, we need to add <router-outlet></router-outlet> in the servers.component.html as shown below

<div class="row">
  <div class="col-xs-12 col-sm-4">
    <div class="list-group">   

      <a
        [routerLink]="['/servers', server.id]"
        [queryParams]="{ allowEdit: server.id === 3 ? '1' : '0' }"
        fragment="loading"
        href="#"
        class="list-group-item"
        *ngFor="let server of servers"
      >
        {{ server.name }}
      </a>
    </div>
  </div>
 

  <div class="col-xs-12 col-sm-4">
    <router-outlet></router-outlet>
  </div>
</div>


ServerComponent / Child Component


Server.component.ts

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params, Router, Data } from "@angular/router";
import { ServersService } from "../servers.service";

@Component({
  selector: "app-server",
  templateUrl: "./server.component.html",
  styleUrls: ["./server.component.css"]
})
export class ServerComponent implements OnInit {
  server: { id: number; name: string; status: string };

  constructor(
    private serversService: ServersService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
this.route.params.subscribe((params: Params) => {
      this.server = this.serversService.getServer(+params["id"]);
    });
  }

  onEdit() {   
this.router.navigate(["/servers", this.server.id, "edit"], {
      relativeTo: this.route,
      queryParamsHandling: "preserve"
    });
  }
//- relative to current route. it tells angular to which route you want to navigate it relatively
}



Server.component.html

<h5>{{ server.name }}</h5>
<p>Server status is {{ server.status }}</p>
<button class="btn btn-primary" (click)="onEdit()">Edit Server</button>


Since both Server and ServerEdit component shares the same parent on clicking Edit, the ServerComponent get replaced with EditServerComponent



Nesting Children’s under a child
We can add child routes to a child route.


{ path: 'product', component: ProductComponent,
    children: [
      { path: 'detail/:id', component: ProductDetailComponent,
          children : [
              { path: 'overview', component: ProductOverviewComponent },
              { path: 'spec', component: ProductSpecComponent },
              { path: '', redirectTo:'overview', pathMatch:"full" }
          ]
      }
    ]
  },


Mapping the action to View

<h1>Product Details Page</h1>

product : {{product.name}}
price : {{ product.price}}

<ul class="nav navbar-nav">
    <li><a [routerLink]="['overview']">OverView </a></li>
    <li><a [routerLink]="['spec']">Specification </a></li>
</ul>

<router-outlet></router-outlet>

<p>
    <a class='btn btn-default' (click)="onBack()">Back to Product List </a>
</p>


When binding a path to the routerlink directive, we use a relative path. A forward slash (/) marks the start of an absolute path. When utilizing a relative path, the router will create the final URL by adding the path to the parent route path.

Both ProductOverviewComponent & ProductSpecComponent are rendered inside the ProductDetailComponent. Hence we need to add <router-outlet></router-outlet> in the Template of ProductDetailComponent.




Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram