Mastering Angular Routing: Lazy Loading & Guards
In single-page applications (SPAs), routing is the mechanism that maps URL paths to specific views. While basic routing gets you from Page A to Page B, scaling an application requires advanced techniques like Lazy Loading and Guards.
Why Lazy Loading Matters
By default, Angular bundles all your code into one large file. As your app grows, this file becomes huge, slowing down the initial load time.
Lazy Loading splits your application into Feature Modules. These modules are only loaded when the user navigates to their specific route.
// app-routing.module.ts
const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
];Protecting Routes with Guards
Not all pages should be accessible to everyone. Admin panels, user profiles, and settings pages need protection. Angular provides Route Guards to handle this.
- CanActivate: Checks if a user can visit a route (e.g., are they logged in?).
- CanDeactivate: Checks if a user can leave a route (e.g., do they have unsaved changes?).
- CanLoad: Prevents lazy loaded modules from even downloading if unauthorized.
Pro Tip: Always place your Wildcard route (**) at the very end of your routes array. Angular checks routes from top to bottom, and the wildcard matches everything. If it's at the top, no other route will ever be reached!