Angular · Lesson 6

Routing & forms

The Angular router (route config, lazy loading, functional guards and resolvers, route params bound to inputs) and typed reactive forms (FormControl<T>, FormGroup, nonNullable, sync and async validators, cross-field validation).

13 min read

In short

  • Routes match in order; the first match wins
  • loadComponent gives each page its own chunk
  • Route params as inputs follow URL changes
  • Guards return true, false or a UrlTree, and aren't security
  • Typed forms: nonNullable, group validators, getRawValue()

Two things every business app has: pages (the router) and forms (reactive forms). Both are full of rules that look obvious until they bite: a route that never matches because another one is listed first, a guard that redirects in a loop, a form value typed string | null everywhere, a validator that makes an optional field required, an async check that leaves the submit button disabled forever.

This topic covers the modern APIs: standalone routes, loadComponent, functional guards and resolvers, route params as component inputs, and typed reactive forms. Snippets that need Angular have no Try button; the exercises rebuild each mechanism in plain TypeScript.

Routes are data

A route config is an array of plain objects, registered once:

// app.routes.ts
import { Routes } from '@angular/router';
import { adminGuard, authGuard, unsavedChangesGuard } from './core/guards';
import { orderResolver } from './orders/order.resolver';
import { NotFoundPage } from './not-found-page';

export const routes: Routes = [
  { path: '', redirectTo: 'orders', pathMatch: 'full' },
  {
    path: 'orders',
    canActivate: [authGuard],
    children: [
      { path: '', loadComponent: () => import('./orders/order-list') },
      { path: 'new', loadComponent: () => import('./orders/new-order'), canDeactivate: [unsavedChangesGuard] },
      { path: ':id', loadComponent: () => import('./orders/order-page'), resolve: { order: orderResolver }, title: 'Order' },
    ],
  },
  { path: 'admin', canMatch: [adminGuard], loadChildren: () => import('./admin/admin.routes') },
  { path: '**', component: NotFoundPage },
];
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes, withComponentInputBinding())],
};

How the router picks a route for /orders/42:

  • It splits the URL into segments (orders, 42) and tries the routes in order. The first match wins, so put new before :id (or new becomes an order id) and '**' last.
  • A route's path matches the start of the remaining segments (pathMatch: 'prefix', the default), and its children must match the rest. A route without children must use up the whole URL.
  • pathMatch: 'full' means "the whole remaining URL". You need it on empty-path redirects: every URL starts with zero segments, so { path: '', redirectTo: 'orders' } with prefix would match everything. (Angular rejects that config.)
  • :id captures a string parameter. A route without component (like orders above) just groups children and shares their guards.

Navigate with links and the Router, passing segments as an array so the router encodes them:

<a [routerLink]="['/orders', order.id]" [queryParams]="{ tab: 'history' }" routerLinkActive="active">{{ order.number }}</a>
<router-outlet />
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({ selector: 'app-order-search', template: `<button (click)="open('A-1007')">Open</button>` })
export class OrderSearch {
  private readonly router = inject(Router); // inject in a field, not inside the click handler

  open(id: string) {
    return this.router.navigate(['/orders', id], { queryParams: { tab: 'history' } });
  }
}

Lazy loading

loadComponent and loadChildren take a function that returns a dynamic import(). The bundler puts that code in a separate chunk, downloaded the first time the route is used, which keeps the first page load small.

  • loadComponent: () => import('./orders/order-page').then((m) => m.OrderPage), or just () => import('./orders/order-page') when the file has a default export.
  • loadChildren: () => import('./admin/admin.routes') loads a whole feature's Routes array (the file's default export, or .then((m) => m.ADMIN_ROUTES) for a named one).
  • A route can have its own providers: [...]. Services provided there exist only for that part of the app, which is how a lazy feature gets feature-level state without polluting the root injector.
  • withPreloading(PreloadAllModules) downloads lazy chunks in the background after the app starts.

Route params as inputs

With withComponentInputBinding(), the router sets the routed component's inputs from the URL and the route config. You don't need ActivatedRoute for the common cases:

import { Component, computed, input, numberAttribute } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Order } from './order';

@Component({ selector: 'app-order-page', templateUrl: './order-page.html' })
export default class OrderPage {
  readonly id = input.required({ transform: numberAttribute }); // from :id, as a number
  readonly tab = input<'summary' | 'history'>(); // from ?tab=..., undefined when absent
  readonly order = input.required<Order>(); // from the resolver named `order`
  readonly invoices = httpResource(() => `/api/orders/${this.id()}/invoices`);
  readonly notFound = computed(() => Number.isNaN(this.id()));
}
  • Sources, from lowest to highest priority: query params, path params, static data, resolver results.
  • An input with nothing in the route is set to undefined, even if it has a default value. (So a removed query param doesn't leave a stale value behind.) Since Angular 22, withComponentInputBinding({ unmatchedInputBehavior: 'undefinedIfStale' }) keeps the default for inputs the route never provided.
  • Since Angular 22, child routes also see their parents' path params (paramsInheritanceStrategy: 'always' became the default), so a child page under orders/:id can have an id input too.
  • Everything from the URL is a string. numberAttribute and booleanAttribute (from @angular/core) convert, and a bad number becomes NaN rather than a silently wrong value.
  • The component is reused when only the params change (/orders/1 to /orders/2). The constructor and ngOnInit don't run again, but inputs update, and everything derived from them (computed, httpResource) follows. Code that read route.snapshot.paramMap.get('id') once in ngOnInit keeps showing order 1: that's the classic bug input binding avoids. Without input binding, use route.paramMap.pipe(switchMap(...)).

Functional guards

Guards are functions. They can inject() services and return true, false, a UrlTree (redirect), a RedirectCommand, or an Observable or Promise of those:

import { inject } from '@angular/core';
import { CanActivateFn, CanDeactivateFn, CanMatchFn, Router } from '@angular/router';
import { AuthStore } from './auth.store';

export const authGuard: CanActivateFn = (route, state) =>
  inject(AuthStore).isSignedIn() || inject(Router).createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });

export const adminGuard: CanMatchFn = () => inject(AuthStore).roles().includes('Admin');

export interface HasUnsavedChanges {
  hasUnsavedChanges(): boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
  !component.hasUnsavedChanges() || confirm('Discard your changes?');
GuardRunsfalse means
canMatchwhile matching, before lazy code loads"pretend this route isn't here": the next route is tried
canActivateafter a route matchedcancel the navigation
canActivateChildbefore any child route activatescancel the navigation
canDeactivatewhen leaving the routestay on the page (unsaved changes)
  • Redirect by returning a UrlTree, not by calling router.navigate() inside the guard and returning false.
  • Several guards: parents run before children. The result is decided by the first guard (in declared order) that doesn't return true.
  • canMatch is the right tool for role-based or feature-flagged areas: users who can't use the area never download its code, and a second route with the same path can serve them something else.
  • Guards are UX, not security. Anyone can call your API without your Angular app. The API checks permissions.

Resolvers

A resolver loads data before the route activates, and the router binds the result to an input with the resolver's name:

import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, of } from 'rxjs';
import { Order, OrderApi } from './order-api';

export const orderResolver: ResolveFn<Order> = (route) => {
  const router = inject(Router);
  return inject(OrderApi)
    .get(route.paramMap.get('id')!)
    .pipe(catchError(() => of(new RedirectCommand(router.parseUrl('/orders/not-found')))));
};

The trade-off: the user sees nothing new until the data arrives (the old page stays, or a blank one on first load). That's fine for small, fast, essential data (the order header). For slow or optional data, load it in the component with httpResource or toSignal and show a skeleton. Resolvers run again when the route's params change.

Typed reactive forms

Reactive forms are typed since Angular 14. A control's type comes from its initial value, plus null:

import { Component, inject } from '@angular/core';
import { FormControl, FormGroup, NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-signup',
  imports: [ReactiveFormsModule],
  templateUrl: './signup.html',
})
export class Signup {
  readonly loose = new FormControl(''); // FormControl<string | null>: reset() sets it to null
  readonly strict = new FormControl('', { nonNullable: true }); // FormControl<string>: reset() restores ''

  private readonly fb = inject(NonNullableFormBuilder); // every control nonNullable
  readonly form = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    displayName: ['', [Validators.required, Validators.maxLength(50)]],
    password: ['', [Validators.required, Validators.minLength(12)]],
    confirm: [''],
    marketingOptIn: [false],
  });

  submit() {
    if (this.form.invalid) {
      this.form.markAllAsTouched(); // show every error now
      return;
    }
    const value = this.form.getRawValue(); // { email: string; displayName: string; ... }
  }
}
<form [formGroup]="form" (ngSubmit)="submit()">
  <input type="email" formControlName="email" />
  @if (form.controls.email.hasError('required') && form.controls.email.touched) {
    <p class="error">Email is required.</p>
  }
  <button type="submit">Create account</button>
</form>
  • nonNullable almost everywhere. A plain FormControl('') is FormControl<string | null> because reset() sets it to null. With nonNullable: true (or NonNullableFormBuilder), reset() restores the initial value and the type is honest.
  • form.value is Partial: disabled controls are left out. form.getRawValue() includes them and has every key.
  • form.controls.email is typed, so a renamed control breaks the build instead of the page.
  • FormArray<FormControl<string>> holds a list of controls (order lines, phone numbers). FormRecord<FormControl<boolean>> holds controls whose keys you only know at runtime (one checkbox per permission).
  • setValue needs every control and throws on a mismatch. patchValue takes any subset.
  • dirty means the user changed it, touched means the user left the field. Programmatic setValue sets neither.

Validators

A validator is a function from a control to ValidationErrors | null. The built-ins follow conventions worth copying in your own:

  • Only Validators.required complains about empty values. minLength, pattern, email and good custom validators let '' and null pass, so an optional field can stay empty.
  • required accepts whitespace. Add a "not blank" validator for names and titles.
  • Validators.pattern('[0-9]+') (a string) is anchored for you; Validators.pattern(/[0-9]+/) (a RegExp) is not.
  • Error keys are part of your API: hasError('minlength'), and the payload (requiredLength, actualLength) feeds the message.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export const notBlank: ValidatorFn = (control: AbstractControl): ValidationErrors | null =>
  typeof control.value === 'string' && control.value !== '' && control.value.trim() === '' ? { blank: true } : null;

// Cross-field: a validator on the group sees every control.
export const passwordsMatch: ValidatorFn = (group: AbstractControl) =>
  group.get('password')?.value === group.get('confirm')?.value ? null : { passwordMismatch: true };

// this.fb.group({ ... }, { validators: [passwordsMatch] })

Cross-field rules belong on the group. A validator on confirm alone can't see password and wouldn't re-run when password changes. The group's validator runs on every change, and its error lives on the group: form.hasError('passwordMismatch').

Async validators return an Observable (or Promise) of errors, for checks that need the server:

import { inject } from '@angular/core';
import { AbstractControl, AsyncValidatorFn } from '@angular/forms';
import { catchError, map, of, switchMap, timer } from 'rxjs';
import { UserApi } from './user-api';

export function usernameAvailable(api = inject(UserApi)): AsyncValidatorFn {
  return (control: AbstractControl) =>
    timer(300).pipe( // debounce inside: Angular unsubscribes when the value changes again
      switchMap(() => api.isUsernameTaken(control.value)),
      map((taken) => (taken ? { usernameTaken: true } : null)),
      catchError(() => of(null)), // or an error key; the server checks again on save anyway
    );
}
  • They run only when all sync validators pass, and the control is PENDING while they run.
  • Make the Observable complete (the docs require it). When you pass a list of async validators, Angular combines them with forkJoin, which waits for every one to complete and uses their last values, so a never-ending one leaves the control PENDING forever. A single validator on its own sets errors on each value it emits, but don't rely on that: end with take(1) or first().
  • A new value cancels the running check. Debounce inside the validator, as above.
  • updateOn: 'blur' (on a control or the whole group) validates when the user leaves the field instead of on every keystroke.

Here is the debounce-and-cancel behaviour with plain RxJS (a fake API that takes 20 ms):

▶ Try
import { delay, map, of, switchMap, timer } from 'rxjs';

const taken = new Set(['ann', 'bo']);
const isTaken = (name: string) => {
  console.log(`  request for "${name}"`);
  return of(taken.has(name)).pipe(delay(20));
};
const usernameAvailable = (value: string) =>
  timer(30).pipe(
    switchMap(() => isTaken(value)),
    map((t) => (t ? { usernameTaken: true } : null)),
  );

// The user types "a", "an", "ann" quickly. Angular unsubscribes from the previous check each time.
let running = usernameAvailable('a').subscribe();
running.unsubscribe();
running = usernameAvailable('an').subscribe();
running.unsubscribe();
usernameAvailable('ann').subscribe((errors) => console.log('result for "ann":', JSON.stringify(errors)));

Server-side validation. The API validates again, and ASP.NET Core answers 400 with ValidationProblemDetails (errors: { Email: ['...'] }). Map those onto the controls with this.form.controls.email.setErrors({ server: messages }) so they show up next to the right field.

Forms and signals

  • toSignal(this.form.valueChanges, { initialValue: this.form.getRawValue() }) gives a signal of the form's value for computeds (a live price total, a "Save" button state).
  • Since Angular 18, control.events is one Observable of value, status, touched, pristine, submit and reset events.
  • Signal Forms (@angular/forms/signals) came in Angular 21 as experimental and are stable since Angular 22: the model is a signal and the form is derived from it. Reactive forms are still fully supported, and they're what you'll find in most existing code.

Common mistakes

  • orders/:id listed before orders/new, or '**' before other routes.
  • An empty-path redirect without pathMatch: 'full'.
  • Reading route.snapshot once in ngOnInit and missing param changes on a reused component.
  • Calling router.navigate() inside a guard instead of returning a UrlTree.
  • Treating guards as security.
  • new FormControl('') everywhere, then ?? '' everywhere. Use nonNullable.
  • Validators.minLength instead of Validators.minLength(3) (a compile error), or Validators.required() (also one).
  • Custom validators that flag empty values, which makes optional fields required.
  • A cross-field rule written as a control validator.
  • An async validator whose Observable never completes, or one that runs on every keystroke without a debounce.
  • Using form.value (Partial, without disabled controls) when you meant form.getRawValue().

How it looks in a real codebase

Side note
  • Each feature exports its routes (orders.routes.ts) and is lazy-loaded from app.routes.ts. Guards live in core/guards, resolvers next to their feature.
  • Forms are built with NonNullableFormBuilder in the component (or in a small form service for a multi-step wizard), and their typed value is sent straight to the API client.
  • Validation messages come from one shared component or pipe that maps error keys to text, so every form says "At least 12 characters" the same way.
  • The backend (ASP.NET Core) validates everything again and returns ProblemDetails. The client maps field errors back onto controls.

The exercises

  1. Match a route path: segments, :params, decoding, query strings.
  2. Write the built-in validators: required, minLength, maxLength, pattern, compose and a custom one.
  3. Route data to component inputs: withComponentInputBinding precedence, numberAttribute and booleanAttribute.
  4. A typed FormControl: nonNullable, reset, dirty and touched, overloads with NoInfer.
  5. A typed FormGroup with cross-field validation: a mapped value type, value versus getRawValue(), mustMatch.
  6. A router with children, redirects, guards and lazy routes: the whole matching algorithm, async.
  7. Async validation with debounce, cancellation and updateOn: the PENDING state machine in RxJS.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app