Chapter 6: Angular Routing and Navigation
Routing and navigation are crucial aspects of building single-page applications (SPAs) in Angular. They allow users to navigate between different views and components within the application. In this chapter, we will explore the implementation of routing in Angular, configuring routes and route parameters, guarding routes with route guards, and implementing lazy loading.
- Implementing Routing in Angular:
To get started with routing in Angular, follow these steps:
Step 1: Create a new Angular project or use an existing one.
Step 2: Install the Angular Router package by running the following command in your project directory:
npm install @angular/router
Step 3: Open the app.module.ts
file and import the RouterModule
from @angular/router
:
import { RouterModule } from '@angular/router';
Step 4: Define your routes in the AppRoutingModule
module. Create a new file app-routing.module.ts
if it doesn’t exist and add the following code:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
- Configuring Routes and Route Parameters:
Angular allows you to configure routes to match specific paths and handle dynamic segments of the URL. Here’s an example of configuring routes with route parameters:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'users/:id', component: UserComponent },
];
In the example above, the second route defines a parameter id
that can be accessed within the UserComponent
. To access the route parameters in your component, inject the ActivatedRoute
service and subscribe to the params
observable:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
userId: string;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.params.subscribe(params => {
this.userId = params.id;
});
}
}
- Guarding Routes with Route Guards:
To protect routes based on user authentication or authorization, you can use route guards. Here’s an example of implementing a simple route guard:
Step 1: Create a new file auth.guard.ts
and add the following code:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = ...; // Check if the user is authenticated
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Step 2: Add the route guard to the desired route configuration:
const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] },
];
- Implementing Lazy Loading:
Lazy loading allows you to load modules on-demand, improving the initial loading time of your application. Here’s an example of lazy loading feature modules:
Step 1: Create a feature module by running the following command:
ng generate module feature --route feature --module app.module
Step 2: Update the route configuration in the app-routing.module.ts
file:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) },
];
- Enhancing Navigation:
Angular provides directives to simplify navigation within your application. Here’s an example of using routerLink
to create navigation links:
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
You can also programmatically navigate using the Router
service. Here’s an example:
import { Router } from '@angular/router';
@Component({
// ...
})
export class MyComponent {
constructor(private router: Router) {}
goToAboutPage(): void {
this.router.navigate(['/about']);
}
}
By understanding and implementing routing and navigation in Angular, you can create dynamic and interactive applications that provide a seamless user experience.