My account

Routing in depth in Angular

The Angular router does more than map URLs to components. Guards decide who may enter or leave a page, canMatch stops even the download of code a user may not see, resolvers load data before the page shows, route params can arrive as component inputs, and preloading makes the next page feel instant. Each step of a navigation has a clear order, and interview questions are about that order.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleAngular 20 code

Author: bezzad

Contents

The problem: an admin area and a lost cart

The basics of routes and loadComponent are in the Angular fundamentals lesson. Now our shop has bigger needs:

  1. The admin area must be only for admins. Today a customer who types /admin sees the page for a moment, then gets sent away.
  2. The checkout page loses data. A customer fills the address, clicks a link by mistake, and the form is gone.
  3. Product pages read the id with a long subscribe on the route params.
  4. The cart page opens slowly the first time, because its code is downloaded only on the click.

What happens in one navigation

1. MatchcanMatchloadChildren2. GuardscanDeactivatecanActivate3. Resolveresolverspage waits4. Activatepage shownURL is finalA "no" here: navigation stops, old page staysor a UrlTree: go somewhere else
A navigation runs in fixed steps. If any guard says no, the navigation stops and the old page stays. Resolvers run only after every guard said yes.
  1. Match: the router finds the route for the URL. canMatch guards run here. Lazy child routes (loadChildren) are downloaded here.
  2. Guards: canDeactivate on the page you leave, then canActivateChild and canActivate on the new route.
  3. Resolve: resolvers load data. The navigation waits for them.
  4. Activate: the new component is created and shown, and the URL in the address bar is final.

Functional guards

A guard is a plain function. It can use inject, and it returns true, false, or a UrlTree (a redirect).

import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(Auth);
  if (auth.isLoggedIn()) return true;
  return inject(Router).createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url },
  });
};
  1. Return a UrlTree to redirect. Do not call router.navigate inside the guard and then return false. With a UrlTree, the router does the redirect as part of the same navigation.
  2. A guard can also return an Observable or a Promise, for example when it must ask the server first. The navigation waits.
  3. Guards are only for the user experience. Anyone can change the JavaScript in their browser. The server must check permissions on every API call.

canMatch: do not even download it

A customer (not an admin) opens /admincanActivatedownload admin.js 380 KBguard: nocode wastedcanMatchguard: nonext route: 404 page0 KB downloadedThe server still checks every admin API call.
With canActivate on a lazy area, the router downloads the admin code first and only then says no. With canMatch, the route is skipped, and the code is never downloaded.
export const adminMatch: CanMatchFn = () => inject(Auth).isAdmin();

export const routes: Routes = [
  {
    path: 'admin',
    canMatch: [adminMatch],
    loadChildren: () =>
      import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES),
  },
  { path: '**', component: NotFound },
];
  1. If canMatch returns false, the router acts as if the route does not exist and tries the next route. Here the customer gets the 404 page.
  2. You can have two routes with the same path and different canMatch guards, for example one dashboard for admins and one for customers.
  3. canMatch replaces the old canLoad guard, which is deprecated.

Route params as inputs

// app.config.ts
provideRouter(routes, withComponentInputBinding());

// product-page.ts, route: 'products/:id'
export class ProductPage {
  readonly id = input.required<string>();
  readonly product = httpResource<Product>(
    () => `/api/products/${this.id()}`,
  );
}
  1. With withComponentInputBinding, path params, query params, route data and resolver results are given to inputs with the same name.
  2. When the user goes from product 7 to product 8, the same component is reused. The id input changes, so everything built from it updates. Code that reads the param only once in the constructor shows the old product. (httpResource is new; check if it is still experimental in your Angular version. A switchMap on the id works too.)

Resolvers: data before the page

export const productResolver: ResolveFn<Product> = (route) =>
  inject(ProductApi).get(route.paramMap.get('id')!);

{ path: 'products/:id', component: ProductPage,
  resolve: { product: productResolver } }
  1. The page opens only when the data is there, so there is no empty page with a spinner.
  2. But the user sees nothing happen while the resolver waits. For slow data, show a loading bar from router events, or load the data inside the page instead.
  3. If the resolver fails, the navigation fails. Handle the error, for example redirect to a “not found” page.

canDeactivate: do not lose the form

export const unsavedGuard: CanDeactivateFn<Checkout> = (page) =>
  !page.form.dirty || confirm('Leave? Your address will be lost.');

The guard gets the component that is being left. It is a good place for “you have unsaved changes”. It does not run when the user closes the tab. For that, use the browser’s beforeunload event.

Preloading: the next page is already here

provideRouter(routes, withPreloading(PreloadAllModules));
  1. After the first page is shown, the router downloads the lazy child routes (loadChildren) in the background.
  2. In a big app, downloading everything wastes the user’s data. Write your own PreloadingStrategy that preloads only routes with a flag in data, such as cart and checkout.
  3. Inside a page, @defer with prefetch on hover or prefetch on viewport does the same for heavy parts.

Route-level providers

A route can have its own providers. Services listed there are created when the user enters that area and are shared by all its child pages. This is good for state that belongs only to the admin area. Remember: they are not destroyed when the user leaves the route.

Common mistakes

Mistake Result Better way
canActivate on a lazy area Every user downloads the admin code. canMatch.
router.navigate inside a guard Two navigations fight. Return a UrlTree.
Guards as the only security Data leaks through the API. Check on the server too.
Reading the id once in the constructor Old product after going to the next one. Input binding, or the paramMap observable.
A slow resolver with no feedback The click seems broken. A loading bar, or load inside the page.
Preloading everything Wasted data on phones. A custom strategy for likely pages.

Summary in 6 lines

  1. A navigation goes: match (canMatch, loadChildren), guards, resolve, activate.
  2. Guards are functions with inject. Return a UrlTree to redirect.
  3. Use canMatch to hide a lazy area. Its code is never downloaded.
  4. withComponentInputBinding gives route params to inputs, and they update on reuse.
  5. Resolvers block the navigation. Show progress, or load inside the page.
  6. canDeactivate protects unsaved forms. Preload only the pages that are likely next.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.