Angular Router enables multi-page navigation without page reloads. This lesson covers route setup, dynamic parameters, lazy loading, and route guards for a
Learn the core concepts of Angular Router and apply them in practical exercises.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'users/:id', component: UserDetailComponent },
// Lazy-loaded feature module
{
path: 'admin',
loadChildren: () => import('./admin/admin.module')
.then(m => m.AdminModule),
canActivate: [AuthGuard]
},
{ path: '**', redirectTo: '' } // 404 fallback
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({ ... })
export class UserDetailComponent implements OnInit {
userId: string = '';
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
// Snapshot: read once on init
this.userId = this.route.snapshot.paramMap.get('id') ?? '';
// Observable: react to param changes in same component
this.route.paramMap.subscribe(params => {
this.userId = params.get('id') ?? '';
this.loadUser();
});
}
goBack() { this.router.navigate(['/users']); }
}
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.auth.isLoggedIn()) return true;
this.router.navigate(['/login']);
return false;
}
}
loadChildren splits your app into separate JavaScript bundles. Users only download the admin bundle when they navigate to /admin. This dramatically improves initial load time for large apps.Before moving on, confirm understanding of these key concepts: