Angular 8 Child Component Routing Configuration to append to Parent Component URL

Updated on: May 27, 2021

In Angular application, we can configure Parent and Child page routing, if you are looking for adding routing in your application for Parent-Child pages, then read the following article to know how can we achieve this:

Parent URL: http://domainName/shops

Child URL 1: http://domainName/shops/add

Child URL 2: http://domainName/shops/update/1

From the above URLs, it is clear that we have a parent page called shops component and we have other two child  pages or sub pages called Add and Update. So here we want to see how we can achieve this type of routing with Angular 6 or Angular 8  applications. There are multiple ways to achieve this, but here we have used simple approach by creating separate component for each child page as shown below:

Step 1: Add Component for shop from following command:

ng g c Shops

Step 2: Add Component for Add Shops using following command:

ng g c Shops/Add-Shop

Step 3: Add Component for Update Shops using following command:

ng g c Shops/Update-Shop

Step 4: Now, Open shops.component.html page and add the following code to routing links on Shop page:

<div style="margin:20px;">
    <div style="float:left;"><a routerLink="add">Add</a></div>
    <div style="float:left;margin-left:20px;"><a routerLink="update/1">Update</a></div>
</div>

Step 5: Now, open update-shop.component.ts file and add following code to read parameters passed to Update Shop URL:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-update-shop',
  templateUrl: './update-shop.component.html',
  styleUrls: ['./update-shop.component.css']
})
export class UpdateShopComponent  implements OnInit {
  shopId: number;
  constructor(private router: ActivatedRoute) { }
  ngOnInit() {
    this.router.params.subscribe(params => {
      this.shopId = params.shopId;
  });
}
}

Step 7: Now, Open update-shop.component.html to read the Shop Id Parameter as shown below:

<div>Update Shop Page for ShopId: {{shopId}}</div>

Step 8: Now, add the routing configuration for parent page and all its child pages in app-routing.module.ts page as shown below:

const routes: Routes = [
  { path: 'shops', component: ShopsComponent, pathMatch: 'full'},

  { path: 'shops/add', component: AddShopComponent, pathMatch: 'full'},
  { path: 'shops/update/:shopId', component: UpdateShopComponent, pathMatch: 'full' }
];

Step 9: Now run the Angular project from following command and see the output:

ng serve -o

You can try above method to achieve linking of navigation of child pages to parent pages in Angular application.

Like the above approach, there is another approach to specify children component while specifying routing for parent component, you can use that approach from here: http://www.techtutorhub.com/article/Angular-8-Implementing-Children-Component-Routing-in-Parent-Component-routes/59