Angular — Guards
What are Guards?
Guards control access to routes based on conditions.
CanActivate Guard
// auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true;
}
router.navigate(['/login']);
return false;
};
Using Guard
const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [authGuard]
}
];
CanDeactivate Guard
export const unsavedChangesGuard: CanDeactivateFn<any> = (component) => {
if (component.hasUnsavedChanges()) {
return confirm('You have unsaved changes. Leave anyway?');
}
return true;
};
CanMatch Guard
export const canMatchGuard: CanMatchFn = (route, segments) => {
const authService = inject(AuthService);
return authService.hasRole(route.data['role']);
};
Guard Types
| Guard | Purpose |
|---|---|
| canActivate | Before entering route |
| canActivateChild | Before child routes |
| canDeactivate | Before leaving route |
| canMatch | Before matching route |
Mini Practice
- Create an auth guard
- Protect admin routes
- Add unsaved changes guard
- Use role-based guards
Up Next
Continue with Interceptors — HTTP interceptors.
Related Topics
Frequently Asked Questions about Guards
What is Guards in Angular?
Guards is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Guards?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Guards.
Why is Guards important in Angular?
Guards is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.