How to do Child Routing in Angular 2

Posted By : Deepak Rawat | 30-Jun-2017

Hey guys,

 

Sometimes in our application we need to access some route within other routes, for that we can use child routing.

 

Suppose there is a ecommerce website where we can see the specifications of a product after clicking on the tab inside the product detail page, when user clicks on that tab then we have to show the specification for that product.

 

So if user selects the product with id 25, and click on the specification tab then we have to show the specification for that product, then our route will be:

 

localhost:3000/product-details/25/specification

 

Here specification is the child route of product-details/:id , these types of child routing are only accessible within product detail.

 

Now our route with child route will look like this :

 
 

export const routes: Routes = [
  { path: '', redirectTo: 'product-list', pathMatch: 'full' },
  { path: 'product-list', component: ProductList },
  { path: 'product-details/:id', component: ProductDetails,
    children: [
      { path: '', redirectTo: 'overview', pathMatch: 'full' },
      { path: 'overview', component: Overview },
      { path: specification, component: Specs }
    ]
  }
];
 

Now you are wondering that where these child routes will be displayed? For showing these route we will use <router-outlet></router-outlet> inside the parent component just like we have used it on the root component.

 

For above case the <router-outlet></router-outlet> will be inside the ProductDetail component.

 
 
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
 
@Component({
  selector: 'product-details',
  template: `
    <p>Product Details: {{id}}</p>
    <!-- Product information -->
    <nav>
      <a [routerLink]="[specification]">Technical Specs</a>
    </nav>
    <router-outlet></router-outlet>
    <!-- Specification components get added here by the router -->
 
  `
})
export default class ProductDetails implements OnInit, OnDestroy {
}
 

Note: Always handle blank path in all for all the child route like this { path: '', redirectTo: 'overview', pathMatch: 'full' }.

 
 
 

About Author

Author Image
Deepak Rawat

Deepak is a Web and Mobile application Sr. Lead Frontend developer and good working experience with JQuery , AngularJS , Javascript and PhoneGap. His hobbies are listening to music and photography.

Request for Proposal

Name is required

Comment is required

Sending message..