Route guards run before or during navigation to enforce rules: authentication, unsaved changes, or role-based access. They return true, false, or a UrlTree redirect.
Guard types
CanActivate— allow entering a route?CanDeactivate— allow leaving when a form is dirty?Resolve— prefetch data before the component renders
Functional guards (modern style)
Angular 15+ favors functional guards with inject() instead of class-based guards—same semantics, less boilerplate.
Important interview questions and answers
- Q: What happens when CanActivate returns false?
A: Navigation is cancelled; you may redirect viaUrlTreeto a login page. - Q: Guard vs HTTP interceptor?
A: Guards gate routes; interceptors attach to HTTP requests (auth headers, error mapping).
Self-check
- Name one scenario for CanDeactivate.
- What does a resolver prefetch?