Routing & Navigation
Angular Route Guards
A route guard decides whether navigation may proceed. CanActivate protects a route, CanDeactivate warns before leaving an unsaved form, and CanMatch decides whether a route is even considered.
What is Route Guards in Angular?
A route guard decides whether navigation may proceed. CanActivate protects a route, CanDeactivate warns before leaving an unsaved form, and CanMatch decides whether a route is even considered.
Route Guards example
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) return true;
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }How this works
Returning a UrlTree redirects instead of simply blocking, and carrying returnUrl lets the login page send the user back where they were heading.
Key points to remember
- Functional guards replaced the older class-based guard interfaces.
- A guard may return boolean, UrlTree, Promise or Observable of those.
- CanDeactivate is how you implement "you have unsaved changes" prompts.
- Guards are UI convenience only — the API must enforce real authorisation.
Common mistakes with Route Guards
- Treating guards as security; anyone can bypass client-side code.
- A guard that never completes its Observable, freezing navigation.
Angular Route Guards— Interview Questions & FAQs
Are Angular route guards secure?+
No. They control which components render in the browser, nothing more. Every protected endpoint must verify the session or token on the server independently.
