What is a route guard in Angular, and what is it commonly used for?
Short answer
A route guard is a function that runs before a route is activated, deciding whether navigation should be allowed to continue, redirected elsewhere, or blocked entirely.
Advertisement
AModel answer
A route guard is a function that runs before a route is activated, deciding whether navigation should be allowed to continue, redirected elsewhere, or blocked entirely. A very common use is protecting pages that require a user to be logged in, redirecting anonymous visitors to a login page instead.
export const authGuard: CanActivateFn = () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) return true;
router.navigate(['/login']);
return false;
};
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }Real-world example
A banking app automatically redirects any visitor who is not logged in away from the account dashboard page and back to the login screen, using a route guard applied to that specific protected route.
Likely follow-ups
- How would you also remember the page a user was trying to visit, so they land there after logging in?
- What is the difference between canActivate and canActivateChild?
Related topics