Route Guards: Protect Pages Like a Pro
Use guards to block access to routes unless a user is authenticated or has a role.
Guards decide whether navigation is allowed. This is how you protect routes like `/dashboard`. ## Example: simple auth guard (functional guard style) ```ts import { CanActivateFn, Router } from '@angular/router'; import { inject } from '@angular/core'; export const authGuard: CanActivateFn = () => { const router = inject(Router); const isLoggedIn = localStorage.getItem('token'); if (isLoggedIn) return true; router.navigate(['/login']); return false; }; ``` ## Use it in a route ```ts { path: 'dashboard', loadComponent: () => import('./dashboard.component').then(m => m.DashboardComponent), canActivate: [authGuard] } ``` ## Best practice note Guards are for navigation control. You still must enforce security on the backend too. > Next: Lazy loading to speed up big apps.