Child Routing in Angular 4

What is child routing ?

Whenever we want to change inside content of a page beside header footer. So there we need to create a nested router-outlet.

And with this we need to add children attribute in our routing file.


Use there children

–TS File (app-routing.module.ts)

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

import { RecipesComponent } from "../recipes/recipes.component";
import { RecipeStartComponent } from "../recipes/recipe-start/recipe-start.component";
import { RecipeDetailComponent } from "../recipes/recipe-detail/recipe-detail.component";
import { RecipeEditComponent } from "../recipes/recipe-edit/recipe-edit.component";

const appRoutes: Routes = [
    { path: '', redirectTo: '/recipes', pathMatch: 'full'},
    { path: 'recipes', component: RecipesComponent, children: [
        { path: '', component: RecipeStartComponent},
        { path: 'new', component: RecipeEditComponent},
        { path: ':id', component: RecipeDetailComponent},
        { path: ':id/edit', component: RecipeEditComponent}
    ] },
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [RouterModule]
})

export class AppRoutingModule {}

You can see we have already router-outlet in app.component.html file.

But for child routing we need to add one more router-outlet into recipes.component.html file.

Add new router-outlet in recipes component

<router-outlet></router-outlet>

Leave a Reply

Your email address will not be published. Required fields are marked *