What are Angular guards?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Angular topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Angular route guards are interfaces that control access to routes. They can prevent navigation to a route, prevent navigation away from a route, or preload data for a route. Types: (1) CanActivate: determines if a route can be activated. Used for authentication: return true to allow, false or UrlTree to redirect. canActivate: [AuthGuard]; (2) CanActivateChild: same as CanActivate but for child routes; (3) CanDeactivate: determines if you can leave a route. Used for "unsaved changes" warnings — return false to stay, true to leave. Generic: CanDeactivate<ComponentWithUnsavedChanges>; (4) CanLoad / CanMatch (Angular 15+): determines if a lazy module can be loaded. Prevents downloading the module code if the user shouldn't have access. Modern functional guards (Angular 14+): guards can now be plain functions instead of classes: export const authGuard: CanActivateFn = (route, state) => { return inject(AuthService).isLoggedIn() ? true : inject(Router).createUrlTree(["/login"]); };. Using guards in routes: { path: "dashboard", component: DashboardComponent, canActivate: [authGuard] }. AuthGuard example: check if user is authenticated → if yes, return true → if no, navigate to login with return URL: return this.router.createUrlTree(["/login"], { queryParams: { returnUrl: state.url } }). Resolvers: not technically guards but route lifecycle hook that pre-fetches data before navigation completes: resolve: { userData: UserResolver }.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Angular codebase.