0
0
AngularConceptBeginner · 3 min read

What is canActivate Guard in Angular: Explanation and Example

In Angular, the 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.

typescript
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 {}
Output
If userToken exists in localStorage, navigating to '/dashboard' shows DashboardComponent; otherwise, user is redirected to '/login'.
🎯

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 true to allow or false to 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.
They are essential for protecting pages that require login or special permissions.
Implement guards as injectable services that Angular calls before navigation.
Use canActivate to redirect unauthorized users to login or other pages.
This guard helps keep your app secure and user-friendly.