Sub topic 7
Guarding a whole subtree with canActivateChild
This chapter assumes you can write a functional canActivate guard and return a UrlTree. It also assumes you know how nested children routes work.
The problem it solves
Suppose an admin section has ten child routes. You could add canActivate: [adminGuard] to each one, but a new child can easily miss the guard. canActivateChild goes on the parent route instead. The router then runs it before it activates any child of that parent.
A guard for children
A CanActivateChildFn receives the child route snapshot being activated, not the parent's. That lets one guard make per-child decisions, for example by reading data from the child route.
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 role = childRoute.data['role'] as string | undefined;
if (!role || auth.hasRole(role)) {
return true;
}
return router.createUrlTree(['/forbidden'], {
queryParams: { from: state.url },
});
};This example assumes AuthService has a hasRole(role: string): boolean method. Attach the guard to the parent:
import { Routes } from '@angular/router';
import { roleChildGuard } from './role-child.guard';
export const routes: Routes = [
{
path: 'admin',
canActivateChild: [roleChildGuard],
children: [
{
path: 'users',
data: { role: 'admin' },
loadComponent: () => import('./users.component').then(m => m.UsersComponent),
},
{
path: 'reports',
data: { role: 'analyst' },
loadComponent: () => import('./reports.component').then(m => m.ReportsComponent),
},
],
},
];A user with only the analyst role can open /admin/reports. A request for /admin/users returns a UrlTree, which redirects to /forbidden.
When it runs
- It runs for every navigation that activates a child under the parent. This includes moving between siblings, such as
/admin/usersto/admin/reports. - It runs before the child's own
canActivate, so you can combine both. Put shared rules on the parent and specific rules on the child. - It returns the same types as other guards:
boolean,UrlTree,RedirectCommand, or anObservableorPromiseof those.
Common mistakes
- Putting it on a leaf route. A route with no children never triggers it.
- Expecting the parent's snapshot. The first argument is the child being activated. Read
childRoute.data, not the parent's data. - Assuming it replaces
canMatch. It does not stop lazy-loaded code from downloading. UsecanMatchfor that, as covered in a later chapter.
Exercise
You put canActivateChild: [roleChildGuard] on the admin route. A user is already on /admin/users and clicks a link to /admin/reports. Does the guard run again, and which route snapshot does it receive?
Show answer
Yes. It runs again because a child under the parent is being activated. It receives the snapshot of the child being activated, reports, so childRoute.data['role'] is 'analyst'.