Types of Guards
Angular provides several types of guards for different scenarios:Guard interfaces are defined in
packages/router/src/models.ts starting at line 857. The router executes guards using the logic in packages/router/src/operators/check_guards.ts.Functional Guards (Recommended)
Modern Angular uses functional guards with theinject() function for dependency injection:
CanActivate Guard
Controls whether a route can be activated:auth.guard.ts
routes.ts
Multiple Guards
You can apply multiple guards to a single route:admin.guard.ts
routes.ts
Guards execute in order. If any guard returns
false or redirects, subsequent guards won’t execute.CanActivateChild Guard
Protects child routes:parent-auth.guard.ts
routes.ts
CanDeactivate Guard
Prevents users from leaving a route with unsaved changes:unsaved-changes.guard.ts
form.component.ts
routes.ts
CanMatch Guard
Determines if a route configuration can be used:feature-toggle.guard.ts
routes.ts
CanMatch guards are useful for A/B testing, feature flags, and conditional route loading. Unlike CanActivate, they prevent the route from being recognized at all.Async Guards
Guards can return Observables or Promises for async operations:permissions.guard.ts
async-auth.guard.ts
RedirectCommand
UseRedirectCommand for more control over redirects:
redirect.guard.ts
RedirectCommand is defined in packages/router/src/models.ts:118 and provides fine-grained control over navigation behavior during redirects.Data Resolvers
Resolvers fetch data before a route activates:user.resolver.ts
routes.ts
user-detail.component.ts
With Component Input Binding
user-detail.component.ts
Class-Based Guards (Legacy)
While functional guards are recommended, class-based guards are still supported:auth.guard.ts
Guard Execution Order
When multiple guards are present, they execute in this order:- canDeactivate - Current route’s deactivation guards
- canMatch - Route matching guards
- canLoad - Lazy loading guards (deprecated, use canMatch)
- canActivateChild - Parent route’s child activation guards
- canActivate - Route activation guards
- resolve - Data resolvers
routes.ts
Real-World Example
Comprehensive guard setup for an enterprise application:app.routes.ts
Best Practices
Use Functional Guards
Prefer functional guards with
inject() over class-based guards for better tree-shaking and simplicity.Return UrlTree for Redirects
Return a
UrlTree from guards instead of calling router.navigate() to let the router handle the redirect.Handle Errors Gracefully
Always handle errors in async guards and provide fallback behavior.
Keep Guards Focused
Each guard should have a single responsibility. Combine multiple guards instead of creating complex logic in one.
Next Steps
Lazy Loading
Learn how to implement lazy loading to optimize your application
Router Overview
Review the fundamentals of Angular routing
