In Angular, Route Guards are used to control access to routes. They act like gatekeepers—allowing or preventing navigation to a route based on some logic, such as authentication, role permissions, or unsaved changes. Angular provides five types of route guards. Let’s go through them step by step.
1. Types of Route Guards
Guard | When It Runs | Purpose |
---|---|---|
CanActivate | Before activating a route | Determines if a route can be accessed |
CanActivateChild | Before activating child routes | Checks access for child routes |
CanDeactivate | Before leaving a route | Checks if the user can leave a route (e.g., unsaved changes) |
Resolve | Before route is activated | Pre-fetch data before loading the component |
CanLoad | Before lazy-loaded module is loaded | Prevents loading of lazy-loaded modules |
2. Implementing CanActivate
Guard
a) Generate a guard
ng generate guard auth
This creates a guard class implementing CanActivate
.
b) Example AuthGuard
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const loggedIn = !!localStorage.getItem('token'); // simple auth check
if (!loggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
c) Protect a route
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
3. CanDeactivate
Example
Used when you want to prevent leaving a route with unsaved changes.
export interface CanComponentDeactivate {
canDeactivate: () => boolean;
}
@Injectable({ providedIn: 'root' })
export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
Component implementation:
export class EditProfileComponent implements CanComponentDeactivate {
changesSaved = false;
canDeactivate(): boolean {
if (!this.changesSaved) {
return confirm("You have unsaved changes. Do you really want to leave?");
}
return true;
}
}
Route setup:
{ path: 'edit-profile', component: EditProfileComponent, canDeactivate: [UnsavedChangesGuard] }
4. CanLoad
Example
Prevents lazy-loaded modules from loading unless a condition is met.
export class AuthGuard implements CanLoad {
canLoad(): boolean {
return !!localStorage.getItem('token'); // only allow if logged in
}
}
// In routes
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule), canLoad: [AuthGuard] }
Summary
- Guards control access to routes.
CanActivate
→ before entering route.CanDeactivate
→ before leaving route.CanActivateChild
→ for child routes.CanLoad
→ for lazy-loaded modules.Resolve
→ pre-fetch data before route activation.