Sub topic 7
Guarding a whole subtree with canActivateChild
This chapter assumes you can write a functional canActivate guard with inject() and return a UrlTree to redirect. It also assumes you know how nested children routes work. The earlier chapters cover both.
The problem: one guard per child does not scale
Suppose an /admin area has a dozen child pages. They all need the same check, such as "the user is logged in and has a role." You could add canActivate: [authGuard] to every child. That works until someone adds a thirteenth child and forgets the guard.
Putting canActivate on the parent does not fix this. A parent's canActivate runs when the router activates the parent. If the user is already inside /admin/users and navigates to /admin/reports, the parent stays active, so its canActivate does not run again. The router checks only the new child.
canActivateChild is declared once on the parent and runs for every route activated beneath it.
Declaring canActivateChild
A canActivateChild guard is a function of type CanActivateChildFn. It takes the same two arguments as canActivate, but the first one is the snapshot of the child route being activated, not the parent.
import { inject } from '@angular/core';
import { CanActivateChildFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const roleChildGuard: CanActivateChildFn = (childRoute, state) => {
const auth = inject(AuthService);
const router = inject(Router);
const requiredRole = childRoute.data['role'] as string | undefined;
if (!auth.isLoggedIn()) {
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
}
if (requiredRole && !auth.hasRole(requiredRole)) {
return router.createUrlTree(['/forbidden']);
}
return true;
};The guard reads childRoute.data['role'], so each child states what it needs and the guard stays generic. The route configuration looks like this:
import { Routes } from '@angular/router';
import { roleChildGuard } from './role-child.guard';
export const routes: Routes = [
{ path: 'login', loadComponent: () => import('./login.component').then(m => m.LoginComponent) },
{ path: 'forbidden', loadComponent: () => import('./forbidden.component').then(m => m.ForbiddenComponent) },
{
path: 'admin',
canActivateChild: [roleChildGuard],
children: [
{ path: '', pathMatch: 'full', redirectTo: 'users' },
{
path: 'users',
data: { role: 'admin' },
loadComponent: () => import('./admin-users.component').then(m => m.AdminUsersComponent),
},
{
path: 'reports',
data: { role: 'auditor' },
loadComponent: () => import('./admin-reports.component').then(m => m.AdminReportsComponent),
},
],
},
];The admin route has no component, so it is a componentless parent that only groups its children. This is the usual place for canActivateChild. A new child added under admin is protected automatically.
The guard is not called for admin itself, only for routes beneath it. A route with no component and only an empty child can still be matched, so keep in mind that the guard fires for the child, not for the grouping route.
When the guard runs
The guard runs once for each child route that the navigation activates. Three cases are worth knowing:
- Entering from outside. Going from
/hometo/admin/usersruns the guard forusers. - Moving between siblings. Going from
/admin/usersto/admin/reportsruns the guard forreports, even thoughadminstays active. This is the case a parentcanActivatemisses. - Deeper nesting. The guard applies to descendants at any depth. If
usershas its ownchildren, theadminguard also runs for each of those grandchildren. In every call,childRouteis the route being activated.
The router also reruns guards when a route's parameters change, according to the route's runGuardsAndResolvers option. Its default is 'paramsChange'. Going from /admin/users/1 to /admin/users/2 therefore runs the guard again, but changing only a query parameter does not.
Where it sits in the guard order
When a navigation has several kinds of guards, the router does not run them in the order you might expect from reading the route tree. It first checks canDeactivate and canActivateChild guards, from the deepest route up to the top. It then checks canActivate guards from the top down. A later chapter covers the full order, including canMatch and resolvers. For now, remember that canActivateChild on a parent runs before canActivate on the child it protects.
This has a practical effect. If the parent's canActivateChild returns false or a UrlTree, the child's own canActivate never runs. You can therefore put broad checks (logged in) on the parent and narrow checks (a specific permission) on individual children without the narrow check running for anonymous users.
Combining with canActivate
canActivateChild and canActivate can sit on the same parent. They answer different questions.
| Property on the parent route | Runs for | Typical use |
|---|---|---|
| `canActivate` | The parent route itself, when it becomes active | Check required to enter the area at all |
| `canActivateChild` | Every child route activated beneath the parent | Check required for each page in the area |
If the check is the same for both, you can reuse one function. A CanActivateFn and a CanActivateChildFn both receive a route snapshot and a router state snapshot, so a function that only uses those two arguments can be assigned to either property. Declaring it with the more specific type that you use it as keeps the types honest.
import { CanActivateChildFn, CanActivateFn } from '@angular/router';
import { roleChildGuard } from './role-child.guard';
export const adminEntryGuard: CanActivateFn = (route, state) =>
roleChildGuard(route, state);Common mistakes
- Putting it on a leaf route.
canActivateChildon a route with no children never runs. UsecanActivatethere. - Expecting it to run on the parent. The parent is not a child of itself. Add
canActivateas well if the parent must be checked. - Relying on
datafrom the wrong route.childRoute.databelongs to the child being activated. Roles set only on the parent are visible to the child only through route data inheritance, which depends on the router'sparamsInheritanceStrategy. Settingdataon each child, as above, avoids the question. - Treating it as security. The guard runs in the browser, so a user can bypass it. The server must enforce the same rule for every API call. A later chapter covers this in detail.
Exercise
A user is on /admin/users and clicks a link to /admin/reports. The admin route has canActivate: [authGuard] and no canActivateChild. Does authGuard run for this navigation? What would you change so that a check runs on every move between admin pages?
Show answer
No. The admin route stays active, so its canActivate does not run again. Only guards on the newly activated child (reports) would run. Move the check to canActivateChild on the admin route, which runs for each child route that is activated beneath it, including this sibling-to-sibling navigation.