πΊοΈ Routing & Navigation
RouterModule configuration, route parameters, lazy loading, route guards, and child routes.
Configuring Angular Router
Angular Router enables navigating between views without reloading the page in single-page applications.
app.routes.ts
TypeScript
import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { NotFoundComponent } from './not-found/not-found.component'; export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'users/:id', loadComponent: () => import('./users/users.component').then(m => m.UsersComponent) }, { path: '**', component: NotFoundComponent } // Wildcard route ];
Router Outlet and Navigation Links
Use `
app.component.html
HTML
<nav>
<a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a>
<a routerLink="/users/42" routerLinkActive="active">User 42</a>
</nav>
<router-outlet></router-outlet>
Route Guards (CanActivate, CanDeactivate)
Functional Route Guards protect routes based on authentication or user permissions.
auth.guard.ts
TypeScript
import { CanActivateFn, Router } from '@angular/router'; import { inject } from '@angular/core'; import { AuthService } from './auth.service'; export const authGuard: CanActivateFn = (route, state) => { const authService = inject(AuthService); const router = inject(Router); if (authService.isLoggedIn()) { return true; } return router.parseUrl('/login'); };