Angular Router : Implementing Child Routes

Introduction

Child routes are necessary to make Angular application effective. We can make any kind of route hierarchy in our project. We must have to learn about child routes in the route configuration. In this article, we will learn about how child routes are added to the parent route configuration. 

Implementing Child Routes

We can implement a child route by adding an array of child route configuration. We can add this array as part of a children key. Now we will see an example of this kind of route configuration:

const appRoutes: Routes = [ 
 {
    path: 'app',
    component: MasterPageComponent,
    children: [
      { path: 'dashboard', 
        component: dashboardComponent }, // Component in the same root module
      { path: 'contacts', 
        loadChildren: "./modules/contacts/contacts.module#ContactsModule", }, 
      //Here contact module is a feature module
    ]
}]

We need to add the directive in the parent component template(Html) file as follows.
<router-outlet></router-outlet>

With such route configuration, the available routes will be /app, /app/dashboard, /app/contacts.

Implementing child routes inside the child routes

We can implement child routes inside the child route as well. 

const routes: Routes = [
  { path: '', component: HomeComponent, children: [
    { path: 'app', component: MasterComponent, children: [
    { path: 'dashboard', component: dashboardComponent }, 
         // Component in the same root module
    { path: 'contacts', loadChildren: "./modules/contacts/contacts.module#ContactsModule",}, //Here contact module is a feature module
     ]},
    ]},
    { path: '**', component: PageNotFoundComponent }
  ] }
];

In this above example, the available routes will be /, /app, /app/dashboard, /app/contacts.

Routes without components

We have seen that every route has a path and component mentioned. But componentless routes are also there. We can have a parent route without any component defined.

const routes: Routes = [
  { path: '', component: HomeComponent, children: [
    { path: 'app', children: [
      { path: 'dashboard', component: DashboardComponent, children: [
        { path: 'map', component: DashboardMapComponent }
      ] },
    ] },
    { path: '***', component: PageNotFoundComponent }
  ] }
];

Here we can see that we have a path app with no component present in the route configuration. But this path has children routes defined. 
So now the available routes will be /, /app/dashboard, /app/dashboard/map.

Note:  When there is no component defined in the parent route configuration, then the DashboardComponent will be inserted in the HomeComponent's router outlet instead.

Comments