← Back to Angular, page 3

angular-0044 · Hard senior

Which router features help in a large Angular application: canMatch, route-level providers, title handling, navigation error handling and view transitions?

canMatch lets the router choose between routes (or skip lazy code) by a runtime condition such as a feature flag or role. Route-level providers create scoped services for a route tree. withViewTransitions animates page changes with the browser API, and withNavigationErrorHandler centralises failed navigations. Together they structure large apps without extra libraries.

Full answer

In a small app the route list is a flat table. In a large one it carries architecture decisions.

canMatch. A normal guard (canActivate) runs after the router has matched a route. A canMatch guard runs while matching. If it returns false, the router acts as if the route did not exist and tries the next route with the same path. Two uses follow:

  • Feature flags and roles: serve NewCheckoutComponent to users with a flag and the old one to everybody else, on the same URL.
  • Security of the bundle: for a lazy route, a failing canMatch means the code chunk is never downloaded.

Route-level providers. A route can declare providers: [CheckoutDraft]. The router creates an environment injector for that route and its children. State lives as long as the user is inside the area. When the user leaves, the service is destroyed. This is a clean way to scope state without global stores.

Titles. Set title: 'Courses' or a resolver function on each route, and a custom TitleStrategy for a common format such as "Courses | Schoolabe". It improves accessibility, because screen readers announce the title on navigation.

View transitions. withViewTransitions() uses the browser's View Transition API for animated page changes. Browsers without support fall back to no animation. Use the onViewTransitionCreated hook to adjust it.

Errors. withNavigationErrorHandler(handler) receives failures such as a lazy chunk that did not load or a resolver that threw. It can log, show a message, or return a RedirectCommand to go elsewhere. Without it, the error goes to the global error handler.

Other settings: withInMemoryScrolling restores scroll position and handles anchors, withComponentInputBinding binds route data to inputs, and withRouterConfig changes behaviour such as onSameUrlNavigation: 'reload'.

typescript
import { Component, Injectable, inject, signal } from '@angular/core';
import {
  CanMatchFn,
  NavigationError,
  RedirectCommand,
  Router,
  Routes,
  provideRouter,
  withComponentInputBinding,
  withInMemoryScrolling,
  withNavigationErrorHandler,
  withViewTransitions,
} from '@angular/router';
import { ApplicationConfig } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class FlagService {
  private readonly on = signal(new Set<string>(['newCheckout']));

  isOn(flag: string): boolean {
    return this.on().has(flag);
  }
}

export const requireFlag =
  (flag: string): CanMatchFn =>
  () =>
    inject(FlagService).isOn(flag);

@Injectable()
export class CheckoutDraft {
  readonly items = signal<string[]>([]);
}

@Component({ selector: 'app-new-checkout', template: `<p>New checkout</p>` })
export class NewCheckoutComponent {
  readonly draft = inject(CheckoutDraft);
}

@Component({ selector: 'app-old-checkout', template: `<p>Old checkout</p>` })
export class OldCheckoutComponent {}

@Component({ selector: 'app-error-page', template: `<p>Something went wrong</p>` })
export class ErrorPageComponent {}

export const routes: Routes = [
  {
    path: 'checkout',
    title: 'Checkout',
    canMatch: [requireFlag('newCheckout')],
    providers: [CheckoutDraft], // one draft per visit to this route tree
    component: NewCheckoutComponent,
  },
  // Same path: used when the flag is off, because canMatch above returned false.
  { path: 'checkout', title: 'Checkout', component: OldCheckoutComponent },
  { path: 'error', component: ErrorPageComponent },
];

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withComponentInputBinding(),
      withViewTransitions(),
      withInMemoryScrolling({ scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled' }),
      withNavigationErrorHandler((error: NavigationError) => {
        console.error('Navigation failed', error.url, error.error);
        return new RedirectCommand(inject(Router).parseUrl('/error'));
      }),
    ),
  ],
};

Angular 20.3, type-checked. The flag service is a plain class here. In a real app it would read remote configuration.

Key points

  • `canMatch` runs during matching, can choose between routes on one path, and can prevent lazy chunk downloads.
  • Route `providers` scope services to a route tree.
  • `title` plus a `TitleStrategy` gives consistent page titles.
  • `withViewTransitions`, `withNavigationErrorHandler`, and `withInMemoryScrolling` are one-line router features.

Common mistakes

  • Using `canActivate` for feature flags, which still downloads the lazy chunk and leaves no fallback route.
  • Putting route-scoped state in the root injector, so it never resets.
  • Forgetting that the order of routes matters when `canMatch` falls through to the next one.

Follow-ups

  • How does `canMatch` differ from `canActivate` for a lazy route?
  • How would you animate only some navigations with view transitions?
  • When is a route-level provider better than a root service?

Tips

  • Lead with `canMatch` versus `canActivate`. It is the most common senior routing question.
  • Tie each feature to a real need: flags, scoped state, accessibility, error recovery.
  • Mention title handling for accessibility. Many candidates forget it.

Evaluation rubric

  • Explains canMatch correctly, including lazy code behaviour.
  • Understands scoped providers.
  • Knows the router feature functions.