Child Routes in Angular
Child routes in Angular allow you to create nested routes, enabling more complex navigation structures. This tutorial covers the basics of setting up and using child routes effectively in your Angular applications.
Setting Up Child Routes
To set up child routes, you need to define them in your route configuration:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { ParentComponent } from './parent/parent.component';
import { ChildComponent } from './child/child.component';
const routes: Routes = [
{ path: 'parent', component: ParentComponent, children: [
{ path: 'child', component: ChildComponent }
]}
];
@NgModule({
declarations: [AppComponent, ParentComponent, ChildComponent],
imports: [BrowserModule, RouterModule.forRoot(routes)],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: 'Parent Component
',
})
export class ParentComponent { }
// child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: 'Child Component
',
})
export class ChildComponent { }
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { }
// app.component.html
Navigating to Child Routes
Use the routerLink directive to navigate to child routes:
// app.component.html
Using RouterOutlet for Nested Views
Use the router-outlet directive to display nested views in the parent component:
// parent.component.html
Parent Component
Key Points
- Child routes allow you to create nested routes, enabling more complex navigation structures.
- Define child routes in your route configuration using the
childrenproperty. - Use the
routerLinkdirective to navigate to child routes. - Use the
router-outletdirective to display nested views in the parent component.
Conclusion
Child routes in Angular provide a powerful way to manage complex navigation structures by allowing nested routes. By understanding and using child routes effectively, you can create dynamic and user-friendly applications with seamless navigation. Happy coding!
