Skip to content

Angular Routing in Depth

The router is the only part of Angular that owns application-wide state you did not write: the URL. Get it right and the URL becomes a shareable, bookmarkable, back-button-correct description of what the user is looking at. Get it wrong and you end up with state that the URL does not describe, a back button that does the wrong thing, guards that block navigation without explaining why, and a bundle that ships the admin console to every anonymous visitor.

Routing is also where three separate concerns collide — navigation, authorisation and data loading — and most routing bugs come from conflating them.

  • Route — a configuration object mapping a URL path to a component or a set of child routes.
  • Route config — the Routes array, matched top to bottom, first match wins.
  • ActivatedRoute — a service giving the current route’s params, query params, data and URL, as observables plus a static snapshot.
  • Navigation — the whole process from a URL change to activated components.
  • Guard — a function that decides whether a navigation may proceed.
  • Resolver — a function that fetches data before the route activates.
  • Outlet — <router-outlet>, the placeholder where a route’s component renders.
  • Route injector — the child EnvironmentInjector created by a route’s providers.

A navigation is a pipeline that can be cancelled at any stage:

URL change
↓ NavigationStart
Recognition — match the URL against the route config (canMatch runs here)
↓ RoutesRecognized
Guards — canDeactivate (leaving), canActivate / canActivateChild (entering)
↓ GuardsCheckEnd
Resolve — run resolvers; navigation is BLOCKED until they complete
↓ ResolveEnd
Activation — instantiate components, fill outlets
↓ NavigationEnd | NavigationCancel | NavigationError | NavigationSkipped

Three things follow, and they answer most router questions:

  • canMatch runs during matching; the other guards run after. That is why canMatch returning false falls through to the next matching route, while canActivate returning false cancels the navigation outright.
  • Resolvers block. The old view stays on screen while they run. A slow resolver is a frozen application with no visible feedback — the single most common routing UX bug.
  • Every navigation ends in exactly one completion event. If you are tracking navigation state, that is the invariant to build on.
app.routes.ts
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'orders', component: OrderList },
{ path: 'orders/:id', component: OrderDetail },
{ path: '**', component: NotFound },
];
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};
<nav>
<a routerLink="/orders" routerLinkActive="active" ariaCurrentWhenActive="page">Orders</a>
</nav>
<router-outlet />

Two rules hiding in four routes:

  • Order matters. The config is matched top to bottom and the first match wins. '**' must be last; 'orders/:id' must come after any literal 'orders/new'.
  • path: '' matches the empty segment, not “anything.” Combine it with pathMatch: 'full' when redirecting from the root, or the redirect matches every URL prefix and you get an infinite loop.

Enable it once and route data arrives as ordinary component inputs:

provideRouter(routes, withComponentInputBinding());
@Component({ /* ... */ })
export class OrderDetail {
readonly id = input.required<string>();
private readonly api = inject(OrderApiClient);
readonly order = httpResource(() => `/api/orders/${this.id()}`);
}

No ActivatedRoute, no subscription, no manual cleanup, and the component becomes trivially testable — you can set the input directly without a router at all. All route data binds this way: path params, matrix params, query params, static data, and resolved values.

Two details that bite:

  • The router assigns undefined when no route data matches an input key — for example an absent optional query param. Include undefined in the type, or supply a default via transform:

    readonly page = input(1, { transform: (v: string | undefined) => Number(v ?? 1) });
  • Query-param binding can be turned off when you manage query params separately: withComponentInputBinding({ queryParams: false }).

private readonly route = inject(ActivatedRoute);
// Reactive — fires on every change, including param-only changes.
readonly orderId = toSignal(this.route.paramMap.pipe(map((p) => p.get('id'))));
// Static — the value at the moment of reading. Does NOT update.
readonly initialId = this.route.snapshot.paramMap.get('id');

The snapshot trap: navigating from /orders/1 to /orders/2 reuses the component by default. The snapshot read in the constructor never re-runs, so the page shows order 1’s data at URL /orders/2. Either subscribe to paramMap, or use component input binding, which handles this correctly.

Use paramMap / queryParamMap rather than the raw params / queryParams objects: they give you get, getAll and has, and getAll is the only correct way to read a repeated query parameter (?tag=a&tag=b).

Query params versus route params versus matrix params

Section titled “Query params versus route params versus matrix params”
Kind Looks like Use for
Route param /orders/42 Identity — what is being shown
Query param /orders?status=open&page=2 Modifiers — filtering, sorting, pagination
Matrix param /orders;view=grid Options scoped to one URL segment

The rule of thumb: if changing it should change what resource you are looking at, it is a route param; if it changes how you are looking at the same resource, it is a query param. Query params also survive navigation with queryParamsHandling:

this.router.navigate([], {
relativeTo: this.route,
queryParams: { sort },
queryParamsHandling: 'merge', // 'merge' keeps others, 'preserve' keeps all, omit to replace
});

Matrix params are genuinely rare. They exist for the case where an option belongs to one segment of a nested route rather than to the whole URL, and most applications never need them.

Four kinds, all plain functions, all running in an injection context so inject() works.

Guard Runs On false
canMatch During URL matching Falls through to the next matching route
canActivate Entering a route Cancels navigation
canActivateChild Entering any child of a route Cancels navigation
canDeactivate Leaving a route Cancels navigation

All four can return boolean, a UrlTree or RedirectCommand, or a Promise/Observable of those — the router takes the first emitted value and unsubscribes, so an observable that emits repeatedly only ever has its first value used.

export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isAuthenticated()
? true
: router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};

Return a UrlTree to redirect. Do not return false and then call router.navigate(). The false-plus-navigate pattern races: the cancellation and the new navigation are two separate operations, and the browser history ends up wrong — the user presses Back and lands on the page they were just bounced off, which bounces them again.

Because rejection falls through rather than cancelling, canMatch lets the same path resolve to different components:

const routes: Routes = [
{ path: 'dashboard', component: AdminDashboard, canMatch: [isAdmin] },
{ path: 'dashboard', component: UserDashboard },
];

It also runs before the lazy chunk is fetched. A canActivate on a lazy route downloads the chunk and then refuses; canMatch refuses first. For a feature flag or a role-gated module, canMatch saves the download.

It runs for every child route beneath the parent, including grandchildren — twice for a two-level nesting. Keep it cheap; do not put a network call in it.

export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
component.hasUnsavedChanges() ? confirm('Discard unsaved changes?') : true;

Type the guard against a small interface rather than a concrete component, so one guard serves every editable screen. Note that confirm() is a blocking browser dialog; a real application usually returns an Observable<boolean> from a modal service instead.

The official documentation is blunt about this, and it is worth repeating in full: never rely on client-side guards as the sole source of access control. All JavaScript running in a browser can be modified by the person running the browser. A guard prevents an honest user from reaching a screen that would not work for them. It does not prevent anyone from calling the API. Authorisation is enforced on the server, always, in addition to any guard.

A resolver fetches data before activation, so the component renders with data already present:

export const orderResolver: ResolveFn<Order> = (route) =>
inject(OrderApiClient).getOrder(route.paramMap.get('id')!);
const routes: Routes = [
{
path: 'orders/:id',
component: OrderDetail,
resolve: { order: orderResolver },
},
];

With withComponentInputBinding(), the resolved value arrives as an input named after the resolve key:

readonly order = input.required<Order>();

Resolvers block navigation — design around it

Section titled “Resolvers block navigation — design around it”

The old page stays on screen with no feedback while a resolver runs. That is why the official best practices are what they are:

  • Keep resolvers lightweight. Essential data only, not everything the page might eventually want.
  • Handle errors. An unhandled rejection cancels the navigation and the user sits on the old page wondering why the link did nothing.
  • Set reasonable timeouts. A resolver that hangs blocks navigation indefinitely.
  • Give feedback. Drive a progress bar from NavigationStart / NavigationEnd.
  • Cache where sensible. Re-resolving unchanged data on every visit is pure latency.
  • Type the results. route.data['order'] is any at the boundary; give it an interface.

Error handling has three levels, and it is worth choosing deliberately:

// 1. In the resolver — most local, lets you supply a fallback and keep navigating.
export const orderResolver: ResolveFn<Order | null> = (route) =>
inject(OrderApiClient)
.getOrder(route.paramMap.get('id')!)
.pipe(catchError(() => of(null)));
// 2. Application-wide, at bootstrap.
provideRouter(routes, withNavigationErrorHandler((e) => {
inject(ErrorReporter).report(e);
return inject(Router).createUrlTree(['/error']);
}));
// 3. By subscribing to NavigationError events, for logging and telemetry.

Resolvers run parent to child, and a child resolver can read the parent’s resolved data through route.parent?.data. That is the correct way to express “load the user, then load that user’s posts” without two round trips of guessing.

The modern alternative is to skip the resolver and let the component load its own data with httpResource or resource, rendering a skeleton while loading. That gives instant navigation with progressive content rather than a frozen old page. Prefer it unless you specifically need the route to fail when the data is unavailable — for example, a 404 route that must not activate for a missing record.

const routes: Routes = [
{
path: 'orders',
loadComponent: () => import('./orders/orders-portal').then((m) => m.OrdersPortal),
},
{
path: 'admin',
canMatch: [isAdmin],
loadChildren: () => import('./admin/admin.routes').then((m) => m.adminRoutes),
providers: [AdminFeatureState],
},
];
  • loadComponent for a single lazy component.
  • loadChildren for a whole feature’s route config — the natural chunk boundary.
  • providers creates a child EnvironmentInjector for the subtree: services there are visible only to that feature and shared by its screens. The injector is not destroyed on navigation by default (see below).

Lazy loading is the single highest-leverage bundle optimisation in a routed application, and it costs almost nothing to adopt.

Lazy loading trades initial bundle size for a delay on first navigation. Preloading buys that delay back by fetching chunks in the background:

provideRouter(routes, withPreloading(PreloadAllModules));

NoPreloading is the default; PreloadAllModules fetches every lazy chunk after the initial navigation completes. PreloadAllModules is fine for small and medium applications. For larger ones, be selective:

@Injectable({ providedIn: 'root' })
export class SelectivePreloading implements PreloadingStrategy {
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
return route.data?.['preload'] ? load() : of(null);
}
}

Then mark routes with data: { preload: true }.

Three real costs to weigh, per the official guidance: preloaded chunks consume bandwidth (which matters on metered mobile connections), consume memory, and compete for connections — browsers cap concurrent requests, so aggressive preloading immediately after load can queue behind the images and API calls that the user is actually waiting for. Preload the two or three routes users go to next, not everything.

orders.routes.ts
export const ordersRoutes: Routes = [
{
path: '',
providers: [OrdersFeatureState],
canActivateChild: [authGuard],
children: [
{
path: '',
component: OrderList,
title: 'Orders',
},
{
path: 'new', // literal before parameterised
component: OrderEditor,
canDeactivate: [unsavedChangesGuard],
title: 'New order',
},
{
path: ':id',
component: OrderDetail,
resolve: { order: orderResolver },
title: (route) => `Order ${route.paramMap.get('id')}`,
children: [
{ path: '', redirectTo: 'summary', pathMatch: 'full' },
{ path: 'summary', component: OrderSummary },
{ path: 'history', component: OrderHistory },
],
},
],
},
];
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withInMemoryScrolling({ scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled' }),
withViewTransitions(),
withPreloading(SelectivePreloading),
withNavigationErrorHandler((error) => {
inject(ErrorReporter).report(error);
return inject(Router).createUrlTree(['/error']);
}),
),
],
};

Points worth extracting:

  • title sets document.title per route, statically or from a function. It is a genuine accessibility feature — screen-reader users rely on the title to know the page changed — and it is routinely forgotten.
  • withInMemoryScrolling restores scroll position on Back and enables #fragment anchors. Without it, the back button lands the user at the top of a long list they had scrolled halfway down.
  • canActivateChild on the parent protects the whole feature with one declaration rather than repeating canActivate on each child.
  • The 'new' route precedes ':id'. Reversed, /orders/new matches :id with id === 'new' and the resolver requests a nonexistent order.
  • redirectTo: 'summary' with pathMatch: 'full' gives the detail route a default tab.

Matching is depth-first with backtracking over a tree. The router walks the config in order, consuming URL segments. Failing to match a subtree backtracks and tries the next candidate. This is why canMatch can fall through — it is evaluated as part of the match, so a rejection is a match failure like any other.

Router.navigate returns Promise<boolean>. It resolves true on success, false on cancellation, and rejects on error. Ignoring the return value means silently swallowing failed navigations — a common source of “the button does nothing.”

Navigations are serialised. Triggering a navigation while one is in flight cancels the first (NavigationCancel). Rapid programmatic navigation therefore drops intermediate states rather than queueing them.

Component reuse is the default. Navigating between two URLs that resolve to the same component with different params reuses the instance: no re-construction, no ngOnInit. That is a performance feature and the direct cause of the snapshot trap. RouteReuseStrategy is the extension point if you need different behaviour, and implementing it badly is an easy way to leak detached views.

Route injectors are child EnvironmentInjectors. They scope visibility, not lifetime. By default Angular does not destroy the injector of a route the user has left, so services provided there keep their state.

To have unused route injectors destroyed, opt in:

provideRouter(routes, withAutoCleanupInjectors());

withAutoCleanupInjectors() is public API from Angular v22.2 (it was previously withExperimentalAutoCleanupInjectors(), now deprecated). After each navigation it destroys the injectors of inactive routes that the RouteReuseStrategy is not currently storing. With the default strategy, or one that extends BaseRouteReuseStrategy, that means an injector is destroyed once its routes are inactive. A custom strategy that does not extend BaseRouteReuseStrategy must implement shouldDestroyInjector(route) and return its stored handles from retrieveStoredRouteHandles(), or the router may destroy injectors a detached handle still needs.

If “reset when the user leaves” is a requirement, design it explicitly rather than relying on injector teardown — for example, reset the feature state from the feature’s root component via inject(DestroyRef).onDestroy(...).

Named outlets let one URL drive several regions independently:

<router-outlet />
<router-outlet name="sidebar" />
this.router.navigate([{ outlets: { sidebar: ['filters'] } }]);
// URL becomes /orders(sidebar:filters)

The bracket syntax is unusual-looking but it makes a multi-pane layout genuinely bookmarkable. Use it sparingly — the URLs get hard to read quickly.

View transitions. withViewTransitions() hooks the router into the browser’s View Transitions API for cross-fade and morph animations between routes. It degrades to no animation where the API is unsupported.

Custom matchers. matcher: (segments, group, route) => UrlMatchResult | null replaces path matching entirely — for version-prefixed URLs, locale-aware paths, or matching rules a path string cannot express. Note the performance cost: a custom matcher runs on every navigation attempt against that route, so keep it to string inspection and avoid anything expensive.

Router events for a progress bar. Navigation has no built-in loading UI, and resolvers make one necessary:

readonly navigating = toSignal(
this.router.events.pipe(
filter((e) =>
e instanceof NavigationStart ||
e instanceof NavigationEnd ||
e instanceof NavigationCancel ||
e instanceof NavigationError,
),
map((e) => e instanceof NavigationStart),
),
{ initialValue: false },
);

Every navigation ends in exactly one of NavigationEnd, NavigationCancel, NavigationError or NavigationSkipped, so this cannot get stuck on — provided you handle all four.

withDebugTracing() logs every router event to the console. It is the fastest way to understand why a navigation went where it did. Development only — it is noisy and it costs.

Returning false from a guard and then navigating. Races with the cancellation and corrupts history. Return a UrlTree.

Reading snapshot in a component that can be reused. Stale data on param-only navigation. Subscribe, or use component input binding.

Subscribing to route.params without unsubscribing. ActivatedRoute observables live as long as the route. Use takeUntilDestroyed(), toSignal, the AsyncPipe, or component input binding.

Heavy work in a resolver. Navigation blocks with no feedback. Fetch the minimum, or move loading into the component with resource.

Guards as the security model. Covered above; it bears repeating because it is the most consequential routing mistake there is.

Wildcard or redirect routes placed too early. First match wins, so a '**' in the middle of the config silently swallows everything below it.

redirectTo without pathMatch: 'full' on an empty path. { path: '', redirectTo: '/home' } matches every URL prefix and loops.

Storing UI state in a service instead of the URL. Filters, sorting and pagination in a service are not shareable, not bookmarkable, and reset on refresh. If a user would reasonably send someone the link, it belongs in query params.

Everything eagerly loaded. A route config with no loadComponent or loadChildren ships every screen to every visitor.

Symptom Cause Fix
Component does not update on param change Read from snapshot; instance reused Subscribe to paramMap, or use input binding
Blank page after navigating Missing <router-outlet>, or a child route with no parent outlet Check outlets at every nesting level
Infinite redirect loop redirectTo on path: '' without pathMatch: 'full' Add pathMatch: 'full'
Wrong component for a URL Route order; a parameterised path shadows a literal Move literal paths above parameterised ones
Back button returns to a blocked page Guard returned false then navigated Return a UrlTree
Navigation appears to do nothing Resolver still running, or one that errored withDebugTracing(); add a progress indicator
NG04002: Cannot match any routes No matching route and no wildcard Add a '**' route
Scroll starts at the top on Back Scroll restoration not configured withInMemoryScrolling({ scrollPositionRestoration: 'enabled' })
Lazy chunk downloads then access is refused canActivate on a lazy route Use canMatch so the chunk is never fetched
Guard’s inject() throws NG0203 Called after an await inside the guard Inject at the top of the function body
Memory grows across navigations Un-torn-down subscriptions, or a custom RouteReuseStrategy retaining handles Audit subscriptions; destroy detached handles

Lazy-load at feature boundaries. loadChildren per feature is the default shape; anything more granular usually costs more in requests than it saves in bytes.

Preload selectively, and after the critical path. Preloading competes with images and API calls for a limited connection pool.

canMatch over canActivate for gated lazy routes. Refuse before the download, not after.

Prefer in-component loading over resolvers for anything that is not required for the route to be valid. Instant navigation with a skeleton beats a frozen page, and it lets the shell render while the data arrives.

Keep route configs flat where you can. Deep nesting means more guard evaluations per navigation — remember canActivateChild fires for every descendant level.

Beware RouteReuseStrategy. Caching detached route handles to make Back instant also keeps whole component trees alive, with their subscriptions and timers. If you implement one, destroy the handles you stop using; the router will not do it for you.

Client-side guards are not authorisation. Enforce every access decision on the server. A guard is a user-experience feature.

Lazy chunks are public files. A canMatch guard stops a normal user fetching the admin chunk; it does not stop anyone requesting the file directly from the origin. Do not put anything sensitive in client code, and never assume “they cannot reach that route” means “they cannot read that code.”

Do not put secrets or personal data in the URL. Query params land in browser history, server access logs, proxy logs, and the Referer header sent to third-party origins. Tokens, session identifiers and email addresses do not belong there.

Validate returnUrl before redirecting to it. The ?returnUrl= pattern is an open-redirect vector when the value is used unchecked. Accept only same-origin relative paths.

skipLocationChange hides the URL, not the data. It is a presentation choice with no security meaning.

Two approaches, both worth having.

Guards and resolvers are plain functions, so the simplest test calls them inside an injection context. Provide the router (the guard injects Router to build its redirect) and any services it uses:

it('redirects anonymous users to login', () => {
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{ provide: AuthService, useValue: { isAuthenticated: () => false } },
],
});
const result = TestBed.runInInjectionContext(() =>
authGuard({} as ActivatedRouteSnapshot, { url: '/orders' } as RouterStateSnapshot),
) as UrlTree;
expect(result).toBeInstanceOf(UrlTree);
expect(TestBed.inject(Router).serializeUrl(result)).toBe('/login?returnUrl=%2Forders');
});

For component-level routing behaviour, RouterTestingHarness navigates for real against a test route config:

TestBed.configureTestingModule({
providers: [
provideRouter([{ path: 'orders/:id', component: OrderDetail }], withComponentInputBinding()),
],
});
const harness = await RouterTestingHarness.create();
const component = await harness.navigateByUrl('/orders/42', OrderDetail);
expect(component.id()).toBe('42');

The testing guide has a complete guard example with both approaches.

And components that take route data as inputs need no router in their tests at all — which is the strongest practical argument for withComponentInputBinding(). See the testing guide.

Decision Favours Costs
Component input binding No subscriptions, testable without a router One more global feature to enable and understand
ActivatedRoute observables Full control, access to the whole route tree Subscription management; snapshot pitfalls
Resolver Component renders with data present; route can fail Navigation blocks; needs its own loading UI
In-component resource Instant navigation, progressive rendering Component handles loading and error states
canMatch Refuses before download; enables path overloading Runs during matching, so keep it fast
canActivate Straightforward, familiar Downloads the chunk before refusing
PreloadAllModules Simple; every route feels instant Bandwidth and memory; competes with critical requests
Custom preloading Precise More code, and a policy to keep current
State in the URL Shareable, bookmarkable, back-button-correct URL design becomes public API
State in a service Simple, no URL design Not shareable; lost on refresh

“canActivate or canMatch for a role-gated lazy feature?” canMatch, for two reasons. It runs during route matching, before the lazy chunk is fetched, so an unauthorised user never downloads the code. And rejection falls through to the next matching route rather than cancelling the navigation, so you can declare a fallback component on the same path. canActivate runs after matching, which means the chunk is already downloaded by the time you refuse.

“Navigating from /orders/1 to /orders/2 doesn’t update the view. Why?” The router reuses the component instance when only the parameters change — no re-construction, no ngOnInit. Anything read from route.snapshot in the constructor is therefore frozen at the first value. Fix it by subscribing to paramMap, or better, by enabling withComponentInputBinding() so the id input updates like any other input and everything derived from it recomputes.

“How do you handle a slow resolver?” First, question whether it should be a resolver. Resolvers block navigation with the old page still on screen and no feedback, so they suit data the route is invalid without — a record that might 404 — and not data the page can render around. If it stays a resolver: keep it to the minimum payload, cache, set a timeout, handle errors so a failure does not silently cancel the navigation, and drive a progress bar from the router events. Otherwise move the load into the component with httpResource and render a skeleton, which gives instant navigation.

“Walk me through a navigation.” NavigationStart. Recognition matches the URL against the config, running canMatch as part of matching and lazy-loading route configs where needed. RoutesRecognized. The guard phase runs canDeactivate for routes being left, then canActivate and canActivateChild for routes being entered. GuardsCheckEnd. The resolve phase runs resolvers parent to child, blocking until they settle. ResolveEnd. Activation instantiates components and fills outlets. Then exactly one of NavigationEnd, NavigationCancel, NavigationError or NavigationSkipped.

“Guards protect your admin routes. Is the admin area secure?” No, and not in a partial way — a guard provides no security at all. All client-side JavaScript can be modified by whoever is running the browser, so any guard can be bypassed, and the lazy chunk is a file on the origin that anyone can request directly. The guard’s job is to stop a legitimate user landing on a screen that would not work for them. Every authorisation decision has to be enforced by the server on every request, and no secret or privileged logic can live in client code.

“When does state belong in the URL?” When a user would reasonably expect to share it, bookmark it, or get it back after a refresh — which covers filters, sorting, pagination, the selected tab, and the open record. Identity goes in path params; modifiers go in query params. State that is genuinely transient (a hover, a half-typed input, a transient toast) stays in the component. The test I use: if someone sends a colleague this link, should they see the same thing? If yes, it is in the URL.