Angular routing for child components

Monir Khan
2 min readSep 27, 2023

Consider the following structure in Angular

smoothie module
mango component
- indian-mango component
- japanese-mango component
smoothie-routing.module.ts
smoothie.module.ts

You want to create a module based routing for this structure. You can do the following.

//smoothie-routing.module.ts
const routes: Routes = [
{
path: 'mango',
children: [
{
path: 'indianmango',
component: IndianMangoComponent
},
{
path: 'japanesemango',
component: JapaneseMangoComponent
},
{
path: '',
component: MangoComponent,
pathMatch: 'full'
},
{
path: '**',
component: PagenotfoundComponent
}
]
}
];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class SmoothieRoutingModule { }

You need to add the SmoothieRoutingModule inside the imports block in SmoothieModule

In the main app routing file you can import it using the code below

{ path: 'smoothie', loadChildren: () => import('./smoothie/smoothie.module').then(m => m.SmoothieModule) },

Now the last stage if you want to create routing between the child components you can use the code below.

// mango.component.html
<nav>
<ul>
<li>
<a class="selected" tabindex="0" > Mango </a>
</li>
<li>
<a [routerLink]="['indianmango']"> Indian mango</a>
</li>
<li>
<a [routerLink]="['japanesemango']"> Japanese mango</a>
</li>
</ul>
</nav>
// indian-mango.component.html
<nav>
<ul>
<li>
<a [routerLink]="['../']"> Mango </a>
</li>
<li>
<a class="selected" tabindex="0"> Indian mango</a>
</li>
<li>
<a [routerLink]="['../japanesemango']"> Japanese mango</a>
</li>
</ul>
</nav>
// japanese-mango.component.html
<nav>
<ul>
<li>
<a [routerLink]="['../']"> Mango </a>
</li>
<li>
<a [routerLink]="['../indianmango']"> Indian mango</a>
</li>
<li>
<a class="selected" tabindex="0"> Japanese mango</a>
</li>
</ul>
</nav>

Using these simple steps you can create basic routes with children and/or nested routes in angular.

If you want to pass parameters you can use the following code.

{
path: 'indianmango/:id', // Define a parameter named 'id'
component: IndianMangoComponent,
},
<a [routerLink]="['../indianmango', 123]">Indian Mango</a>
export class IndianMangoComponent implements OnInit {
constructor(private route: ActivatedRoute) {}

ngOnInit(): void {
// Read the 'id' parameter from the route
const id = this.route.snapshot.params['id'];
console.log('ID parameter:', id);
}
}

--

--