Sub topic 9
Choosing routes at match time with canMatch
This chapter assumes you know the Routes array, lazy loading with loadComponent and loadChildren, and how to write a functional guard with inject(). If not, review those first.
What canMatch does
canMatch runs while the router is still deciding which route configuration matches the URL. If the guard returns false, the router skips that route and keeps looking at the routes after it. canActivate works differently. It runs after a route has matched, and a false result cancels the whole navigation.
This difference has two consequences:
- You can define several routes with the same path and let
canMatchpick one. - For a lazy-loaded route, a failed
canMatchmeans the router never downloads the code. A failedcanActivateon a lazy route can still leave the code downloaded, because the router loads it before the activation guards run.
A guard that hides a lazy route
import { inject } from '@angular/core';
import { CanMatchFn } from '@angular/router';
import { AuthService } from './auth.service';
export const adminMatchGuard: CanMatchFn = () => inject(AuthService).isAdmin();
// In the routes array:
// {
// path: 'admin',
// canMatch: [adminMatchGuard],
// loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
// }For a non-admin, /admin does not match this route. The admin bundle is never requested. The router goes on to the next route, so you should end the array with a wildcard route. Otherwise the user gets a "Cannot match any routes" error.
Swapping one path for two components
Because a skipped route lets matching continue, you can serve different screens from one URL:
import { inject } from '@angular/core';
import { CanMatchFn, Routes } from '@angular/router';
import { AuthService } from './auth.service';
const isAdmin: CanMatchFn = () => inject(AuthService).isAdmin();
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [isAdmin],
loadComponent: () => import('./admin-dashboard.component').then(m => m.AdminDashboardComponent),
},
{
path: 'dashboard',
loadComponent: () => import('./user-dashboard.component').then(m => m.UserDashboardComponent),
},
{ path: '**', loadComponent: () => import('./not-found.component').then(m => m.NotFoundComponent) },
];Admins get AdminDashboardComponent. Everyone else falls through to the second route.
Signature and return values
A CanMatchFn receives the Route and the UrlSegment[] that are being matched. It does not receive an ActivatedRouteSnapshot, because no route is active yet. That means you cannot read route parameters from the first argument. Like other guards, it can return a boolean, a UrlTree, or a Promise or Observable of either. A UrlTree redirects the navigation instead of falling through.
Common errors
- Using
canMatchand expecting a "denied" page. Afalseresult gives a not-found outcome unless a later route catches the URL. - Putting the wildcard route before the guarded routes, which makes it match first.
- Reading
route.paramMapin acanMatchguard. UsecanActivatewhen you need parameters.
Exercise
A route with path: 'reports' has canMatch: [isManager] and loadChildren. A second route with the same path shows an "upgrade" page. What does a non-manager see, and is the reports bundle downloaded?
Show answer
The non-manager sees the upgrade page, because canMatch returned false and the router moved on to the next route with that path. The reports bundle is not downloaded, because the lazy load only happens for a matched route.