Route Guards
Route guards are functions or classes that control navigation in Angular applications. They can prevent navigation, redirect to different routes, or allow navigation to proceed based on custom logic.Import
Guard Types
Angular provides several types of guards for different navigation scenarios:CanActivate
Controls if a route can be activated
CanActivateChild
Controls if child routes can be activated
CanDeactivate
Controls if a route can be deactivated
CanMatch
Controls if a route can be matched
Modern Angular applications use functional guards (functions) instead of class-based guards. Functional guards are more concise and leverage dependency injection through the
inject() function.Guard Result Types
GuardResult
GuardResult, which can be:
true- Allow navigation to proceedfalse- Cancel navigationUrlTree- Redirect to a different URLRedirectCommand- Redirect with navigation options
MaybeAsync
CanActivate
CanActivateFn
ActivatedRouteSnapshot
required
The activated route snapshot containing route parameters, data, and configuration.
RouterStateSnapshot
required
The router state snapshot containing the target URL and routing tree.
true to allow, false to cancel, or UrlTree/RedirectCommand to redirect.
Examples:
CanActivate Interface (Deprecated)
CanActivateChild
CanActivateChildFn
CanDeactivate
CanDeactivateFn
T
required
The component instance being deactivated.
ActivatedRouteSnapshot
required
The current activated route.
RouterStateSnapshot
required
The current router state.
RouterStateSnapshot
required
The target router state.
CanMatch
CanMatchFn
Route
required
The route configuration being evaluated.
UrlSegment[]
required
The URL segments that have not been consumed yet.
PartialMatchRouteSnapshot
The current route snapshot up to this point in matching (optional for backward compatibility).
Unlike
CanActivate, CanMatch prevents the route from being matched at all. If a canMatch guard returns false, the router continues to the next route configuration. This is ideal for feature flags and conditional routing.CanLoad (Deprecated)
CanLoadFn
RedirectCommand
RedirectCommand Class
Guard Execution Order
When multiple guards are present, they execute in the following order:- Route matching:
canMatchguards - Activation:
canActivateguards (from parent to child) - Child activation:
canActivateChildguards (from parent to child) - Deactivation:
canDeactivateguards (when leaving route)
Common Guard Patterns
Combining Multiple Guards
Reusable Permission Guard
Guard with Loading State
Guard with Error Handling
Testing Guards
See Also
Router Class
Router service API
Route Configuration
Configure routes with guards
Route Guards Guide
Complete guide to route guards
Dependency Injection
Using inject() in guards
