Back to course

Protecting Child Routes (CanActivateChild)

The Complete Angular Developer: From Zero to Hero

39. Protecting Child Routes (CanActivateChild)

When using nested routing, we often want to protect all child routes under a parent route (e.g., all routes under /admin). CanActivateChild allows us to apply a single guard to an entire section of the application.

Nested Routes

We define child routes within the children array of a parent route definition. The parent component (AdminComponent) must contain a <router-outlet> for the children to render.

typescript const routes: Routes = [ { path: 'admin', component: AdminComponent, // This component acts as the container canActivate: [AdminGuard], // Protects access to the AdminComponent itself canActivateChild: [AdminGuard], // Protects access to all children children: [ { path: 'users', component: UserManagementComponent }, { path: 'settings', component: SettingsComponent } ] } ];

Implementing CanActivateChild

The guard implements CanActivateChild (in addition to or instead of CanActivate). The logic is typically the same: check authorization.

typescript // admin.guard.ts import { CanActivate, CanActivateChild, ... }

@Injectable({ providedIn: 'root' }) export class AdminGuard implements CanActivate, CanActivateChild {

// Check access for the parent route canActivate(...) { /* check logic here */ return true; }

// Check access for any child route (e.g., /admin/users or /admin/settings) canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { // We can use the route snapshot to check specific permissions if needed console.log(Checking child route: ${childRoute.url}); return this.authService.isAdmin(); } }

This ensures that if the user doesn't have the necessary administrative privileges, they cannot access /admin, /admin/users, or /admin/settings.