Functional Guard in Angular: What It Is and How to Use It
functional guard in Angular is a simple function that controls access to routes by returning a boolean or an observable/promise of a boolean. It replaces traditional class-based guards with a cleaner, easier-to-write function that Angular calls to decide if navigation should proceed.How It Works
Think of a functional guard like a security checkpoint at a door. Instead of having a full security team (a class with methods), you have a single guard function that quickly checks if someone can enter. This function runs when Angular tries to navigate to a route.
The function returns true if access is allowed or false if it is denied. It can also return a promise or observable that resolves to true or false, allowing asynchronous checks like verifying a user’s login status.
This approach is simpler and more direct than the older class-based guards, making your code easier to read and maintain.
Example
This example shows a functional guard that allows navigation only if the user is logged in.
import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { AuthService } from './auth.service'; export const authGuard: CanActivateFn = () => { const authService = inject(AuthService); const router = inject(Router); if (authService.isLoggedIn()) { return true; } else { router.navigate(['/login']); return false; } };
When to Use
Use functional guards when you want a simple, clear way to protect routes in Angular. They are perfect for checking user authentication, roles, or permissions before allowing access.
For example, if you want to prevent users who are not logged in from seeing certain pages, a functional guard can quickly check their status and redirect them if needed.
They are also useful when you want to write less boilerplate code and keep your route protection logic concise and easy to understand.
Key Points
- Functional guards are simple functions that replace class-based guards.
- They return
true,false, or an observable/promise of these. - They make route protection code cleaner and easier to maintain.
- Use Angular's
inject()to access services inside the guard. - Ideal for authentication and authorization checks.