To demonstrate nested routing in Angular 17, let’s create a simple application with a hierarchical structure of components and routes. Angular’s routing allows us to organize the interface into a hierarchy of views, making it easier to manage complex interfaces. In this example, we’ll create a basic app with a parent route and a child route.
Step 1: Setting Up Angular Environment
First, ensure that you have the Angular CLI installed. If not, install it globally using npm:
npm install -g @angular/cli
Then, create a new Angular project:
ng new angular-nested-routes-demo cd angular-nested-routes-demo
Step 2: Generating Components
For our demo, we’ll need a few components:
- A parent component (
ParentComponent
). - Two child components (
ChildOneComponent
andChildTwoComponent
).
Generate these components using the Angular CLI:
ng generate component Parent ng generate component ChildOne ng generate component ChildTwo
Step 3: Setting Up Routing
First, open the app-routing.module.ts
file. This is where we’ll define our routes. We will set up the parent route and nest the child routes within it.
Replace the contents of app-routing.module.ts
with the following:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ParentComponent } from './parent/parent.component'; import { ChildOneComponent } from './child-one/child-one.component'; import { ChildTwoComponent } from './child-two/child-two.component'; const routes: Routes = [ { path: 'parent', component: ParentComponent, children: [ { path: 'child-one', component: ChildOneComponent, }, { path: 'child-two', component: ChildTwoComponent, }, ], }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
Step 4: Updating Components for Navigation
In parent.component.html
, add links to navigate to the child components and an outlet for displaying the child components:
<h2>Parent Component</h2> <nav> <ul> <li><a routerLink="child-one">Child One</a></li> <li><a routerLink="child-two">Child Two</a></li> </ul> </nav> <router-outlet></router-outlet>
Step 5: Running the Application
Now, run your application:
ng serve
Navigate to http://localhost:4200/parent
to see the Parent component. From there, you can navigate to the Child One and Child Two components using the provided links.
This simple example demonstrates the basics of nested routing in Angular 17. By utilizing the children
array in your route configuration, you can easily set up a hierarchy of routes and views within your Angular applications.
Recent Comments