Angular Guards: Protecting Routes and Navigation
Angular Guards: Protecting Routes and Navigation
Angular route guards control access to routes based on conditions like authentication status, user roles, or unsaved changes, ensuring secure and controlled navigation.
Types of route guards:
- CanActivate: Controls if a route can be activated
- CanActivateChild: Controls access to child routes
- CanDeactivate: Prevents leaving a route with unsaved changes
- CanLoad: Prevents lazy-loaded modules from loading
- CanMatch: Determines if a route can be matched
- Resolve: Pre-fetches data before route activation
Functional guards in modern Angular:
- Simple function-based guards instead of class-based
- Use inject() to access services within guard functions
- Cleaner and more composable approach
- Can return boolean, UrlTree, or Observable/Promise
Authentication guard pattern:
- Check if user is logged in via AuthService
- Redirect to login page if not authenticated
- Store the attempted URL for post-login redirect
- Return UrlTree for automatic navigation
Role-based authorization:
- Check user roles against route data requirements
- Use route data to specify required roles
- Redirect unauthorized users to access denied page
- Combine with CanActivateChild for nested protection
Unsaved changes guard:
- Implement CanDeactivate on components with forms
- Prompt user before navigating away from dirty forms
- Use window.confirm or custom modal dialogs
- Check form dirty state programmatically
Guard composition:
- Chain multiple guards on a single route
- Guards execute in order and all must pass
- Use helper functions to compose guard logic
- Share common guard patterns across the application
Route guards are essential for securing Angular applications. With newer Angular versions, functional guards using inject() are much cleaner than the old class-based approach. One important tip: always handle the redirect logic inside the guard itself rather than just returning false, so users get a proper login page or error message instead of a blank screen.