Route Guards and Resolvers
What Is a Guard?
A guard is a function that decides if navigation may happen. It returns true, false or a redirect.
| Guard | Question |
|---|---|
canActivate | May the user open this route? |
canActivateChild | May the user open any child of this route? |
canMatch | Should this route even match (and its lazy code load)? |
canDeactivate | May the user leave this page? |
Auth Guard
typescript
import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) {
return true;
}
// send to login and remember where the user wanted to go
return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};
// routes
{ path: 'account', component: Account, canActivate: [authGuard] }
Role Guard (Factory)
typescript
export const roleGuard = (...roles: string[]): CanActivateFn => () => {
const auth = inject(AuthService);
return roles.includes(auth.role()) || inject(Router).createUrlTree(['/forbidden']);
};
{ path: 'admin', loadChildren: ..., canMatch: [authGuard], canActivate: [roleGuard('admin')] }
canMatch with lazy routes:
canMatch prevents the lazy bundle from being downloaded at all when the user is not allowed. This is better for security-sensitive code.
Unsaved Changes Guard
typescript
export interface HasUnsavedChanges { hasUnsavedChanges(): boolean; }
export const unsavedGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
!component.hasUnsavedChanges() || confirm('You have unsaved changes. Leave this page?');
// component
export class ProfileEdit implements HasUnsavedChanges {
form = inject(FormBuilder).nonNullable.group({ name: [''] });
hasUnsavedChanges() { return this.form.dirty; }
}
// route
{ path: 'profile/edit', component: ProfileEdit, canDeactivate: [unsavedGuard] }
Resolver: Load Data Before the Page
typescript
export const productResolver: ResolveFn<Product> = (route) => {
return inject(ProductService).getById(route.paramMap.get('id')!);
};
{ path: 'products/:id', component: ProductDetail, resolve: { product: productResolver } }
typescript
export class ProductDetail {
product = input.required<Product>(); // with withComponentInputBinding()
}
Resolver trade-off: The page does not appear until the data is ready. For slow requests it is often better to show the page and a loading state instead.
Redirect on Error
typescript
export const productResolver: ResolveFn<Product | null> = (route) => {
const router = inject(Router);
return inject(ProductService).getById(route.paramMap.get('id')!).pipe(
catchError(() => { router.navigate(['/not-found']); return of(null); }));
};
Guards are not security: Guards only hide pages in the browser. The server must check permissions on every API call, because users can change front-end code.
Conclusion
Functional guards decide navigation with inject(). Use canActivate and canMatch for access, canDeactivate for unsaved changes and resolvers when data must exist before a page opens.
Quick Summary: CanActivateFn returns true | UrlTree; server must still enforce security.

