Welcome to our comprehensive guide on Angular Child Routes! In this lesson, we'll delve into the world of nested routes, a powerful feature that allows you to organize your application's routes more effectively. Let's get started!
Child routes are a way to nest routes within other routes. They are particularly useful when you want to structure your application in a hierarchical manner, making it easier to manage complex routing configurations.
To create child routes, we'll first need a parent component and a child component. Let's create a simple parent component called HeroesList and a child component called HeroDetail.
import { Component } from '@angular/core';
@Component({
selector: 'app-heroes-list',
template: `
<h2>List of Heroes</h2>
<router-outlet></router-outlet> // This is where child routes will be displayed
`,
})
export class HeroesListComponent { }import { Component } from '@angular/core';
@Component({
selector: 'app-hero-detail',
template: `
<h2>Hero Detail</h2>
<p>This is the detail view for a hero.</p>
`,
})
export class HeroDetailComponent { }Now, let's define our child routes in the HeroesListComponent's routing module.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HeroesListComponent } from './heroes-list.component';
import { HeroDetailComponent } from './hero-detail.component';
const routes: Routes = [
{ path: '', component: HeroesListComponent },
{
path: ':id', // This route will match any id value
component: HeroDetailComponent, // This component will be displayed when the route is matched
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HeroesListRoutingModule { }In the example above, we've defined a child route that will match any URL with an id parameter. When this route is matched, the HeroDetailComponent will be displayed.
Now that we've defined our child route, let's use it in the parent routing module.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HeroesListComponent } from './heroes-list.component';
import { HeroesListRoutingModule } from './heroes-list-routing.module';
const routes: Routes = [
{ path: 'heroes', component: HeroesListComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes), HeroesListRoutingModule],
exports: [RouterModule],
})
export class AppRoutingModule { }In the parent routing module, we've added our child routing module and defined a route for the HeroesListComponent.
With our setup complete, let's test it out. Start your Angular application and navigate to /heroes. You should see the HeroesListComponent displayed. Now, navigate to /heroes/1 (or any other id), and you should see the HeroDetailComponent displayed with the id parameter passed in.
Which Angular component will be displayed when navigating to `/heroes/1` in the example above?