CanActivateChild
?CanActivateChild
is a route guard in Angular that determines whether a child route of a particular route can be accessed. It's specifically designed for guarding routes that are nested under a parent route. This makes it highly useful when you have a module with child routes that should only be accessible under certain conditions, like user authentication or specific roles.
CanActivateChild
Instead of CanActivate
?At first glance, you might wonder, "Why not just use CanActivate
on the child routes themselves?" While you can use CanActivate
to protect child routes individually, CanActivateChild
provides a more scalable and cleaner approach, especially when:
Setting Up CanActivateChild
Guard
Step 1: Create the Guard
ng generate guard auth/child-route
Step 2: Implement the Guard Logic
import { Injectable } from '@angular/core'; import { CanActivateChild, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root', }) export class ChildRouteGuard implements CanActivateChild { constructor(private authService: AuthService, private router: Router) {} canActivateChild( childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot ): boolean { const isAuthenticated = this.authService.isAuthenticated(); if (!isAuthenticated) { this.router.navigate(['/login']); return false; } return true; } }
Here’s what’s happening in this example:
CanActivateChild
interface.AuthService
.false
, blocking access to the child route.CanActivateChild
Guard to Routesimport { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ParentComponent } from './parent/parent.component'; import { ChildComponent } from './child/child.component'; import { ChildRouteGuard } from './auth/child-route.guard'; const routes: Routes = [ { path: 'parent', component: ParentComponent, canActivateChild: [ChildRouteGuard], // Apply the guard here children: [ { path: 'child1', component: ChildComponent }, { path: 'child2', component: ChildComponent }, ], }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
Now, when a user attempts to access any child route of /parent
, Angular will invoke the ChildRouteGuard
. If the user is authenticated, they can proceed; otherwise, they’ll be redirected to the login page.
CanActivateChild
CanActivateChild
can be used to control access to child routes based on roles. For instance, only users with an Admin role may access certain child routes.CanActivateChild
can be used to restrict access to premium features nested under a parent route.CanActivateChild
CanActivate
guard on each child route individually, you can apply CanActivateChild
once at the parent level.