What is canActivate Guard in Angular: Explanation and Example
canActivate guard is a feature that controls whether a route can be accessed or not. It acts like a gatekeeper that checks conditions before allowing navigation to a page or component.How It Works
The canActivate guard works like a security checkpoint for your app's routes. When a user tries to visit a certain page, Angular asks the guard if it's okay to proceed. The guard runs some logic, like checking if the user is logged in or has permission.
If the guard says yes (returns true), Angular lets the user enter the route. If it says no (returns false), Angular blocks access and can redirect the user elsewhere. This helps protect parts of your app from unauthorized access.
Example
This example shows a simple canActivate guard that allows access only if the user is logged in.
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('userToken'); if (loggedIn) { return true; } else { this.router.navigate(['/login']); return false; } } } // In your routing module: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuard } from './auth.guard'; import { DashboardComponent } from './dashboard.component'; import { LoginComponent } from './login.component'; const routes: Routes = [ { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
When to Use
Use canActivate guards when you want to protect routes from unauthorized users. For example, you might want to block access to a dashboard, profile page, or admin panel unless the user is logged in or has certain permissions.
This guard is helpful in apps where security and user roles matter, ensuring users only see pages they are allowed to access.
Key Points
- canActivate decides if a route can be entered.
- It returns
trueto allow orfalseto block navigation. - Commonly used for authentication and authorization checks.
- Can redirect users if access is denied.
- Implemented as a service that Angular calls before routing.
Key Takeaways
canActivate guards control access to routes by returning true or false.canActivate to redirect unauthorized users to login or other pages.