Angular fundamentals

The rest of this showcase demonstrates senior patterns; this page is the map of what sits under them: the building blocks every one of those patterns is made of. Each fundamental below is its own section: what it is in a line, a small live example or a deep link to where the app already leans on it, and the real source. It's version-agnostic Angular 22: the APIs you'll reach for on any project, whatever this quarter's headline feature is.

The map

Seven fundamentals already have a page of their own. They're listed here so the map is complete, then the sections below cover the rest with live examples or annotated source.

  • Components: standalone, OnPush, signal inputs.
  • Signals: signal/computed/linkedSignal in the deferrable-views demo.
  • Control flow: @if/@for/@switch throughout, the grid most of all.
  • Forms: typed reactive forms, validators, a wizard.
  • RxJS: typeahead, polling, flattening, retry/backoff.
  • Change detection: OnPush and zoneless, measured live.
  • Testing: Vitest, TestBed, fake timers, a11y assertions.

Template & data binding

The four bindings every template is built from: {{ interpolation }}, [property], (event) and the [class]/[style] pair. Type below and toggle the highlight: the same value flows through all four.

Interpolated: edit me

Two-way binding

[(value)] is sugar for a property binding plus an event binding, Angular's "banana in a box". Built on a model() signal (or a ControlValueAccessor), it's how a control both shows a value and reports changes. The rating control on the forms page is the real one: a custom CVA you bind exactly like a native input.

See the rating control (CVA + model) →

Template variables with @let

@let declares a read-only variable in the template. Reach for it when the markup reads the same value more than once and the value deserves a name. The basket below uses it three ways: lines and sub alias signal reads, customer aliases an async pipe result (it arrives after a short delay, and the gold discount follows it), and lineTotal is worked out inside each @for row, then read twice: once for the price, once for the bulk flag. Press "Add one" and every alias that depends on the basket updates.

Loading customer…

  • 2 × A5 notebook$24.00
  • 1 × Fountain pen$48.00
  • 3 × Black ink$28.50
Lines
3
Subtotal
$100.50
Discount
none
Total
$100.50

Three things it can't do, each checked against the real compiler by the spec in the second panel. It can't be assigned from the template: (click)="total = 0" fails with Cannot assign to @let declaration 'total'. It can't be read above its declaration. And it doesn't exist outside the block that declared it, so a @let inside an @if is gone once the block closes.

View source: the basket, four @let declarationslet-demo.ts

Every @let is re-evaluated on each render, so the aliases never go stale. The one inside @for is per row, which is the case no component field can cover.

ts
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import { AsyncPipe, CurrencyPipe } from '@angular/common';
import { type Observable, map, timer } from 'rxjs';
import { Button } from '@foo/ui';

export interface BasketLine {
  readonly sku: string;
  readonly name: string;
  readonly qty: number;
  readonly unitPrice: number;
}

export interface Customer {
  readonly name: string;
  readonly tier: 'standard' | 'gold';
}

// A line at or over this total is flagged "bulk" (and it's the second read of the row's @let).
export const BULK_THRESHOLD = 100;

/*
 * A basket that leans on @let three ways. `lines` and `sub` alias signal reads the template uses
 * several times, so each read happens once per render and the markup names what it means.
 * `customer` aliases an async pipe result, which used to take an `@if (x$ | async; as x)` wrapper
 * just to get a name for it. `lineTotal` is computed inside each @for row, where there's no
 * component field to put it in.
 *
 * Every @let is re-evaluated on each render, so "Add one" changes a signal and every alias that
 * depends on it updates with no extra wiring. They're read-only, though: the template can read
 * them, never assign them (template-rules.spec.ts proves what the compiler rejects).
 */
@Component({
  selector: 'foo-let-demo',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [AsyncPipe, CurrencyPipe, Button],
  template: `
    @let lines = basket();
    @let sub = subtotal();
    @let customer = customer$ | async;
    @let discount = customer?.tier === 'gold' ? 0.1 : 0;

    <p class="let-demo__who">
      @if (customer) {
        Shopping as <strong>{{ customer.name }}</strong> ({{ customer.tier }} tier)
      } @else {
        Loading customer…
      }
    </p>
    <ul class="let-demo__lines" aria-label="Basket lines">
      @for (line of lines; track line.sku) {
        @let lineTotal = line.qty * line.unitPrice;
        <li class="let-demo__line">
          <span class="let-demo__name">{{ line.qty }} × {{ line.name }}</span>
          <span class="let-demo__total">{{ lineTotal | currency: 'USD' }}</span>
          @if (lineTotal >= bulk) {
            <span class="let-demo__bulk">bulk</span>
          }
          <button
            foo-button
            variant="secondary"
            [attr.aria-label]="'Add one ' + line.name"
            (click)="addOne(line.sku)"
          >
            Add one
          </button>
        </li>
      }
    </ul>
    <dl class="let-demo__sums">
      <dt>Lines</dt>
      <dd class="let-demo__count">{{ lines.length }}</dd>
      <dt>Subtotal</dt>
      <dd class="let-demo__subtotal">{{ sub | currency: 'USD' }}</dd>
      <dt>Discount</dt>
      <dd class="let-demo__discount">{{ discount ? '10% (gold)' : 'none' }}</dd>
      <dt>Total</dt>
      <dd class="let-demo__grand">{{ sub * (1 - discount) | currency: 'USD' }}</dd>
    </dl>
  `,
  styles: `
    :host {
      display: grid;
      gap: var(--foo-space-3);
      margin-top: var(--foo-space-4);
      color: var(--foo-color-text);
    }
    .let-demo__who {
      margin: 0;
    }
    .let-demo__lines {
      margin: 0;
      padding: 0;
      list-style: none;
      display: grid;
      gap: var(--foo-space-2);
      max-width: 36rem;
    }
    .let-demo__line {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: var(--foo-space-3);
      padding: var(--foo-space-2) var(--foo-space-3);
      background: var(--foo-color-surface-sunken);
      border: 1px solid var(--foo-color-border);
      border-radius: var(--foo-radius-md);
    }
    .let-demo__name {
      flex: 1 1 10rem;
    }
    .let-demo__total {
      font-variant-numeric: tabular-nums;
      font-weight: var(--foo-weight-semibold);
    }
    .let-demo__bulk {
      padding: 0 var(--foo-space-2);
      border: 1px solid var(--foo-color-border-strong);
      border-radius: var(--foo-radius-sm);
      font-size: var(--foo-text-sm);
    }
    .let-demo__sums {
      display: grid;
      grid-template-columns: max-content max-content;
      gap: var(--foo-space-1) var(--foo-space-4);
      margin: 0;
      font-variant-numeric: tabular-nums;
    }
    .let-demo__sums dd {
      margin: 0;
      font-weight: var(--foo-weight-semibold);
    }
  `,
})
export class LetDemo {
  protected readonly bulk = BULK_THRESHOLD;

  protected readonly basket = signal<readonly BasketLine[]>([
    { sku: 'nb-a5', name: 'A5 notebook', qty: 2, unitPrice: 12 },
    { sku: 'pen-fn', name: 'Fountain pen', qty: 1, unitPrice: 48 },
    { sku: 'ink-bk', name: 'Black ink', qty: 3, unitPrice: 9.5 },
  ]);

  protected readonly subtotal = computed(() =>
    this.basket().reduce((sum, line) => sum + line.qty * line.unitPrice, 0),
  );

  // Arrives late on purpose, so the page shows the async alias before and after it resolves.
  protected readonly customer$: Observable<Customer> = timer(800).pipe(
    map(() => ({ name: 'Aurora Holdings', tier: 'gold' as const })),
  );

  protected addOne(sku: string): void {
    this.basket.update((lines) =>
      lines.map((line) => (line.sku === sku ? { ...line, qty: line.qty + 1 } : line)),
    );
  }
}
View source: what the compiler rejectstemplate-rules.spec.ts

Each fixture is a tiny component compiled by ngtsc with strictTemplates, the dashboard's setting. The test asserts the exact errors, so the rules above are this Angular version's behavior.

ts
// @vitest-environment node
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import ts from 'typescript';
import { performCompilation } from '@angular/compiler-cli';

/*
 * What the template compiler refuses, checked against the real thing. Each fixture is a tiny
 * component compiled by ngtsc with strictTemplates (the dashboard's setting), and the test reads the
 * errors it reports. So the rules quoted on /fundamentals (@let is read-only, exists only after its
 * declaration and only inside its block; `@default never(s);` catches a missing case) are what this
 * Angular version does, not what a doc said once.
 */
const FIXTURES: Record<string, string> = {
  // The shapes the page uses, all of which must compile clean.
  valid: `
    @let lines = items();
    @let first = (first$ | async) ?? 'none';
    <p>{{ lines.length }} items, first {{ first }}</p>
    @for (item of lines; track item.id) {
      @let total = item.qty * item.price;
      <p>{{ total }} {{ total > 100 ? 'bulk' : '' }}</p>
    }
    @let s = state();
    @switch (s.status) {
      @case ('idle') { idle }
      @case ('success') { {{ s.data }} }
      @case ('error') { {{ s.error }} }
      @default never(s);
    }`,
  // A bare check on a union's property: every case is covered, and it still doesn't compile.
  bareNever: `
    @let s = state();
    @switch (s.status) {
      @case ('idle') { idle }
      @case ('success') { {{ s.data }} }
      @case ('error') { {{ s.error }} }
      @default never;
    }`,
  // Switching on a plain string union, the bare form is all it takes.
  bareNeverPrimitive: `
    @let status = state().status;
    @switch (status) {
      @case ('idle') { idle }
      @case ('success') { done }
      @case ('error') { failed }
      @default never;
    }`,
  assign: `
    @let total = items().length;
    <button (click)="total = 0">{{ total }}</button>`,
  beforeDeclared: `
    <p>{{ total }}</p>
    @let total = items().length;`,
  outOfScope: `
    @if (items().length) {
      @let inner = items()[0];
      <p>{{ inner.id }}</p>
    }
    <p>{{ inner.id }}</p>`,
  missingCase: `
    @let s = state();
    @switch (s.status) {
      @case ('idle') { idle }
      @case ('success') { {{ s.data }} }
      @default never(s);
    }`,
};

function fixtureSource(template: string): string {
  return `
import { Component, signal } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { of } from 'rxjs';
type State = { status: 'idle' } | { status: 'success'; data: number } | { status: 'error'; error: string };
@Component({ selector: 'x-fixture', imports: [AsyncPipe], template: \`${template}\` })
export class Fixture {
  items = signal([{ id: 'a', qty: 2, price: 60 }]);
  first$ = of('a');
  state = signal<State>({ status: 'idle' });
}
`;
}

function workspaceRoot(): string {
  let dir = import.meta.dirname;
  while (!existsSync(join(dir, 'nx.json'))) dir = dirname(dir);
  return dir;
}

describe('template rules, as ngtsc reports them', () => {
  const errors: Record<string, string[]> = {};
  let dir = '';

  beforeAll(() => {
    // Inside the workspace so the fixtures resolve @angular/* from its node_modules.
    const tmp = join(workspaceRoot(), 'tmp');
    mkdirSync(tmp, { recursive: true });
    dir = mkdtempSync(join(tmp, 'template-rules-'));
    const files = Object.entries(FIXTURES).map(([name, template]) => {
      const file = join(dir, `${name}.ts`);
      writeFileSync(file, fixtureSource(template));
      return [name, file] as const;
    });

    const { diagnostics } = performCompilation({
      rootNames: files.map(([, file]) => file),
      options: {
        strict: true,
        strictTemplates: true,
        noEmit: true,
        skipLibCheck: true,
        target: ts.ScriptTarget.ES2022,
        module: ts.ModuleKind.Preserve,
        moduleResolution: ts.ModuleResolutionKind.Bundler,
      },
    });

    for (const [name, file] of files) {
      errors[name] = diagnostics
        .filter((d) => d.category === ts.DiagnosticCategory.Error && d.file?.fileName === file)
        .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
    }
  }, 60_000);

  afterAll(() => {
    if (dir) rmSync(dir, { recursive: true, force: true });
  });

  it('compiles the valid uses: signal alias, async alias, per-row value, narrowed @switch', () => {
    expect(errors['valid']).toEqual([]);
  });

  it('rejects assigning to a @let from the template', () => {
    expect(errors['assign']).toEqual(["Cannot assign to @let declaration 'total'."]);
  });

  it('rejects reading a @let before its declaration', () => {
    expect(errors['beforeDeclared']).toEqual([
      "Cannot read @let declaration 'total' before it has been defined.",
    ]);
  });

  it('does not see a @let outside the block that declared it', () => {
    expect(errors['outOfScope']).toEqual(["Property 'inner' does not exist on type 'Fixture'."]);
  });

  it('@default never(s); fails the build when a union member has no @case, naming it', () => {
    expect(errors['missingCase']).toEqual([
      `Type '{ status: "error"; error: string; }' is not assignable to type 'never'.`,
    ]);
  });

  it('a bare @default never; on a union property errors even when every case is handled', () => {
    expect(errors['bareNever']).toEqual([
      "Type 'any' is not assignable to type 'never'.",
      "Property 'status' does not exist on type 'never'.",
    ]);
  });

  it('a bare @default never; is enough when the switch reads a plain string union', () => {
    expect(errors['bareNeverPrimitive']).toEqual([]);
  });
});

Pipes

A pipe is the small, pure transformation that belongs in the template. Built-ins handle the common cases (here date, number and currency format one value three ways), and a custom pipe handles the rest.

  • | date → Oct 29, 2026, 5:03:20 PM
  • | number → 1,234,567.89
  • | currency → $1,234,567.89
  • | relativeTime → 2m ago (custom, pure)
Pipe vs. directive
Both keep logic out of components, but a pipe transforms a value for display while a directive changes an element's behaviour. The [fooAmount] directive is the same accounting format as a pipe could do. It's a directive because it also sets the element's colour and aria, which a pipe can't reach.
View source: a custom pure piperelative-time.pipe.ts

Pure by default: Angular only re-runs it when the input reference changes, which is what makes a pipe cheap to call in a hot template. The doc comment weighs that against the impure alternative.

ts
import { Pipe, PipeTransform } from '@angular/core';

/*
 * A custom pipe: the small, pure transformation that belongs in the template instead of the
 * component. "How long ago was this?" is presentation, derived purely from an input, so it's a
 * pipe rather than a computed field cluttering every component that shows a timestamp.
 *
 * Pipes are pure by default, and that default is load-bearing: Angular only re-runs a pure pipe
 * when its input *reference* changes, so it's cheap to call in a hot template. The cost is that a
 * pure pipe can't react to the clock moving on its own. Its input didn't change, so it isn't
 * re-evaluated. For a relative-time string that's usually fine (the surrounding view re-renders
 * often enough), and far cheaper than the impure alternative below, which Angular re-runs on
 * every change-detection pass. Reach for `pure: false` only when the output really can't be a
 * function of the input alone, and know you're paying for it each tick.
 */
@Pipe({ name: 'relativeTime' })
export class RelativeTimePipe implements PipeTransform {
  transform(value: Date | string | number, now: Date = new Date()): string {
    const then = value instanceof Date ? value : new Date(value);
    const seconds = Math.round((now.getTime() - then.getTime()) / 1000);

    if (seconds < 5) return 'just now';
    if (seconds < 60) return `${seconds}s ago`;

    const minutes = Math.round(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;

    const hours = Math.round(minutes / 60);
    if (hours < 24) return `${hours}h ago`;

    const days = Math.round(hours / 24);
    return `${days}d ago`;
  }
}

Async pipe

| async subscribes to an Observable in the template and (the part that earns it) unsubscribes automatically when the view is destroyed, so a stream can't outlive the component that showed it. The clock below is an interval stream rendered straight through it.

Now: 5:04:55 PM

More streams on the RxJS page →

Custom structural directive

An attribute directive decorates an element that exists; a structural one decides whether it exists at all, and how many times. *fooRepeat="n" is authored from scratch with TemplateRef + ViewContainerRef, the same primitives @for and @if are built on. Drag the count:

  • Row 1
  • Row 2
View source: the *fooRepeat structural directiverepeat.directive.ts

It reconciles instead of rebuilding, adding only new views and removing only the surplus, so it never throws away view state on a count change. The context object is what powers the let i = index binding.

ts
import { Directive, Input, TemplateRef, ViewContainerRef, inject } from '@angular/core';

/*
 * A structural directive authored from scratch: the counterpart to an attribute directive.
 * An attribute directive decorates an element that already exists; a structural one decides
 * whether (and how many times) an element exists at all. `*fooRepeat="n"` stamps its template
 * `n` times:
 *
 *   <li *fooRepeat="3">row</li>   →  three <li>s
 *
 * The star is sugar. `*fooRepeat="n"` desugars to an <ng-template> wrapping the host element,
 * and the directive is handed two tools: a `TemplateRef` (the blueprint of what to stamp) and a
 * `ViewContainerRef` (the slot in the DOM to stamp into). That separation is the whole idea:
 * the directive never touches the host element directly; it asks the container to create or
 * clear views built from the template. Everything @for and @if do is this, one layer down.
 *
 * The context object passed to `createEmbeddedView` is what powers the `let` bindings in a
 * template (`*fooRepeat="3; let i = index"`). We expose a zero-based `index` and the `$implicit`
 * value so `let i` with no key binds to it, the same contract `@for`'s `$index` rides on.
 */
@Directive({
  selector: '[fooRepeat]',
})
export class RepeatDirective {
  private readonly template = inject<TemplateRef<RepeatContext>>(TemplateRef);
  private readonly viewContainer = inject(ViewContainerRef);

  private current = 0;

  /*
   * Reconcile rather than rebuild. When the count drops we remove only the surplus views from
   * the end; when it grows we create only the new ones. Tearing the whole container down and
   * restamping on every change would be correct but wasteful, and it would throw away view
   * state (focus, form values) the user might care about. Same instinct as a keyed @for.
   */
  @Input() set fooRepeat(count: number) {
    const next = Math.max(0, Math.floor(count ?? 0));
    if (next > this.current) {
      for (let i = this.current; i < next; i++) {
        this.viewContainer.createEmbeddedView(this.template, { $implicit: i, index: i });
      }
    } else if (next < this.current) {
      for (let i = this.current; i > next; i--) {
        this.viewContainer.remove(i - 1);
      }
    }
    this.current = next;
  }

  /*
   * The template type-guard that lets `let i = index` type-check. Angular's language service
   * reads this static method to know the shape of the context, so the `let` bindings aren't
   * `any` in strict templates: the structural-directive equivalent of typing an @Input.
   */
  static ngTemplateContextGuard(_dir: RepeatDirective, ctx: unknown): ctx is RepeatContext {
    return true;
  }
}

export interface RepeatContext {
  readonly $implicit: number;
  readonly index: number;
}

Directives

A component is itself a directive: one with a template of its own, rendering a self-contained piece of UI; the design-system catalogue is full of them. But a component is only one of the three kinds of directive Angular gives you, and reaching for it by reflex is how a design system ends up wrapping every native element in a custom tag it didn't need. The other two earn their place. A structural directive changes the shape of the DOM. It adds or removes whole subtrees, which is what @if and @for now do in the framework itself, and what *fooRepeat above does by hand. An attribute directive changes an element that's already there: it attaches behaviour, ARIA, or presentation to a host without introducing a wrapper. [fooTooltip] in the design system is one; so is the [fooAmount] below.

Attribute directives compose in a way components can't. Through host bindings a directive writes classes, styles, attributes and listeners straight onto whatever element it sits on, and signal inputs make those bindings reactive, recomputing the moment an input changes, the same model the components use. hostDirectives takes it further: a component can declare a list of directives to apply to itself, inheriting their behaviour and even re-exposing their inputs, so shared concerns (a focus ring, an analytics hook, an accessibility contract) live in one directive and get pulled into many components by composition rather than copy-paste.

The judgement call worth naming is directive versus pipe. A pipe is the right tool when all you're doing is transforming a value for display: a currency pipe in an interpolation is exactly that, and a directive there would be overkill. [fooAmount] is the case where the line is crossed: it doesn't only format the number into accounting-style USD, it also colours a debit, flags the host with .is-negative, and writes an aria-label that speaks the sign aloud. Formatting and presentation, bound to the host in one place. A pipe can only return a string; it can't touch the element it renders into. The moment the answer has to reach the host, it stopped being a pipe.

[fooAmount]="1284.5"$1,284.50
[fooAmount]="-234"($234.00)
[fooAmount]="0"$0.00
View sourceamount.ts

The whole directive: a signal input for the value, a computed for the accounting format, and the host bindings that paint the text, the negative state, the colour and the spoken label: formatting and presentation in the one place a pipe can't reach.

ts
import { computed, Directive, input } from '@angular/core';

/*
 * The one place USD money is formatted in this monorepo. Both the `[fooAmount]` directive and
 * the data grids (which render plain string cells and so can't host a directive) call this, so
 * a balance reads identically whether a directive painted it or a grid stringified it. One
 * formatter, no second convention to keep in sync.
 */
const usdFormatter = (decimals: number) =>
  new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  });

/*
 * Accounting style: positives read as plain currency, negatives go in parentheses with no
 * minus sign: the fintech convention a finance reader expects, where a stray "-" is easy to
 * miss but "($234.00)" never is. We format the magnitude and add the parentheses ourselves
 * rather than lean on `currencySign: 'accounting'`, because engine support for that option is
 * uneven and a money figure is the wrong place to gamble on a polyfill.
 */
export function formatAccountingUsd(value: number, decimals = 2): string {
  const text = usdFormatter(decimals).format(Math.abs(value));
  return value < 0 ? `(${text})` : text;
}

/*
 * `[fooAmount]` renders a number as accounting-style USD straight into its host element. It's a
 * directive and not a pipe on purpose: a pipe could format the text, but it can't also colour a
 * debit, flag the host with a state class, or speak the sign to a screen reader. Formatting and
 * presentation belong together here, and the only seam that owns both at once is a host-bound
 * directive.
 *
 *   <span [fooAmount]="account.balance"></span>   ->  $1,234.56
 *   <span [fooAmount]="-234"></span>               ->  ($234.00), .is-negative, danger colour
 *
 * The value is written via `[textContent]`, so the host needs no projected content. Point the
 * directive at an empty element and it fills it. Negatives also get an `.is-negative` class and
 * a danger colour, and the `aria-label` always carries the sign in words ("credit"/"debit") so a
 * non-sighted user hears what the parentheses convey visually.
 */
@Directive({
  selector: '[fooAmount]',
  host: {
    '[textContent]': 'formatted()',
    '[class.is-negative]': 'isNegative()',
    '[style.color]': 'isNegative() ? "var(--foo-color-danger-text)" : null',
    '[attr.aria-label]': 'label()',
  },
})
export class Amount {
  // The numeric value to render. Bound as the attribute itself: `[fooAmount]="balance"`.
  readonly value = input.required<number>({ alias: 'fooAmount' });

  // Fraction digits; 2 matches how money is written, but a whole-dollar KPI can pass 0.
  readonly decimals = input(2);

  protected readonly isNegative = computed(() => this.value() < 0);

  protected readonly formatted = computed(() => formatAccountingUsd(this.value(), this.decimals()));

  /*
   * The screen-reader label says the plain magnitude and the direction of the money, not the
   * literal "($234.00)". Punctuation that a screen reader would read as "open paren" tells a
   * listener nothing useful. "234 dollars debit" does.
   */
  protected readonly label = computed(() => {
    const value = this.value();
    const magnitude = Math.abs(value).toLocaleString('en-US', {
      minimumFractionDigits: this.decimals(),
      maximumFractionDigits: this.decimals(),
    });
    return `${magnitude} dollars ${value < 0 ? 'debit' : 'credit'}`;
  });
}

Content projection

<ng-content> lets a component render markup its parent passes in. That's the difference between a card that is your content and one that only wraps a fixed layout. select= gives multiple named slots; the card below projects a header, a body, and a footer into three.

Projected header

This paragraph is the default-slot body, projected straight through from this page into the card's <ng-content>.

The design-system components (card, dialog, alert) all project. It's how one component serves countless layouts.

Dependency injection

Past inject(SomeClass) lie the pieces that make DI a system: an injection token is a typed key for things that aren't classes (config, primitives), and a multi-provider token collects contributions from across the app into one array: the mechanism behind HTTP_INTERCEPTORS and NG_VALIDATORS.

Feature flags (a typed token)
betaCharts is on, experimentalExport is off, read from inject(FEATURE_FLAGS), whose default ships with the token.

2 rules registered via the multi-token. Value is required.

View source: injection token + multi-providerfeature-flags.ts

The token carries its own type and a root factory, so inject(FEATURE_FLAGS) is typed and needs zero wiring. The multi-token returns the array of every rule provided for it, so you add a rule by providing it, never by editing the consumer.

ts
import { InjectionToken, inject } from '@angular/core';

/*
 * DI beyond `inject(SomeClass)`. A class is its own token, but plenty of things you want to
 * inject aren't classes: config objects, primitives, a list of plugins. An `InjectionToken`
 * is a typed key for exactly those: it carries the type, so `inject(FEATURE_FLAGS)` comes back
 * as `FeatureFlags`, not `any`, and it can't collide with another token of the same shape.
 *
 * The `factory` is the default: if nobody provides this token, DI calls the factory in the
 * root injector. That makes the token usable with zero wiring (a sane default ships for free),
 * while any injector up the tree can still override it with its own `provide`. The hierarchy is
 * the point: a route or component can narrow a flag for its subtree without touching the root.
 */
export interface FeatureFlags {
  readonly betaCharts: boolean;
  readonly experimentalExport: boolean;
}

export const FEATURE_FLAGS = new InjectionToken<FeatureFlags>('FEATURE_FLAGS', {
  // `providedIn: 'root'` + factory = a tree-shakable default. No NgModule, no provider array.
  providedIn: 'root',
  factory: () => ({ betaCharts: true, experimentalExport: false }),
});

/*
 * A multi-provider token. With `multi: true`, every `provide` for this token contributes one
 * entry to an array instead of overwriting the last, so independent parts of the app can each
 * register a validation rule (or interceptor, or initializer) without knowing about the others.
 * `inject(VALIDATION_RULES)` returns all of them. This is the exact mechanism behind
 * HTTP_INTERCEPTORS, NG_VALIDATORS, and APP_INITIALIZER.
 */
export interface ValidationRule {
  readonly name: string;
  validate(value: string): string | null;
}

export const VALIDATION_RULES = new InjectionToken<readonly ValidationRule[]>('VALIDATION_RULES');

// A couple of concrete rules a feature could register independently into the multi-token.
export const nonEmptyRule: ValidationRule = {
  name: 'non-empty',
  validate: (value) => (value.trim().length === 0 ? 'Value is required.' : null),
};

export const maxLengthRule: ValidationRule = {
  name: 'max-length',
  validate: (value) => (value.length > 20 ? 'Keep it under 20 characters.' : null),
};

/*
 * A tiny consumer that reads the multi-token and runs every registered rule. It has no idea
 * which rules exist or where they came from. It just asks the injector for the array. Add a
 * rule by providing it; this code never changes.
 */
export function runValidationRules(value: string, rules: readonly ValidationRule[]): string[] {
  return rules.map((rule) => rule.validate(value)).filter((msg): msg is string => msg !== null);
}

// Convenience for the demo component: pull both tokens through field initializers.
export function injectFeatureFlags(): FeatureFlags {
  return inject(FEATURE_FLAGS);
}

Services

A service is a plain class that owns one job and is shared through DI: the place state and the work over it live, so components stay about the view. @Injectable({ providedIn: 'root' }) makes it a tree-shakable singleton: one shared instance, and if nothing injects it the whole class drops from the bundle, which a provider in a module array can't do. Reach for a component- or route-level provider only when you want a fresh, scoped instance per subtree instead of one for the app.

Inside, inject() pulls dependencies. It reads cleaner than a constructor and works in a field initializer, where constructor injection can't. (Constructor injection still reads well when a base class or a clear ordered list of deps is the point.) The discipline that makes a service safe to share is single responsibility: each service does one job. A watchlist tracks watched ids; it doesn't also fetch, persist, and route.

  • Aurora Holdings
  • Borealis Fund
  • Cygnus Capital

Watching 0. The count is a computed off the service's signal, so it tracks every toggle with no wiring in this component.

Exposing state without leaking it
The service keeps a private writable signal and exposes only a public asReadonly() view plus computed derivations (count, isFull). Consumers read and react; they can't reach in and mutate. Every change goes through a named method (add/remove/toggle), so the legal transitions stay in one place. When the data is a stream rather than a value, the same instinct applies: expose an Observable (and keep the Subject private) so consumers subscribe but can't next() into it.

Services are also where data fetching lives: a component asks the service, the service owns the call. The HttpClient & interceptors example below is exactly that shape: QuotesService wraps a typed HttpClient.get and the component never touches HTTP directly.

The same shape runs in production across this app: ThemeService and ToastService in @foo/ui each own one slice of state behind a read-only signal, and the cross-boundary ReviewQueueStore in @foo/state-shared is the federation-spanning version of the same idea. The state pages show where a service grows into a store.

View source: a single-purpose root servicewatchlist.service.ts

providedIn: 'root' for a tree-shakable singleton; inject() for its one dependency; a private writable signal exposed only as an asReadonly() view plus computed derivations, so the component can read the count but can't mutate the set. Every transition is a named method.

ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { FEATURE_FLAGS } from './feature-flags';

/*
 * A single-purpose service: it tracks which account ids are "watched" and nothing else. That
 * narrow remit is the point (one service, one job), so it stays easy to reason about, test and
 * reuse. Anything else a watchlist might eventually want (persistence, a fetch) belongs in its own
 * service this one would depend on, not bolted on here.
 *
 * `providedIn: 'root'` makes it a tree-shakable singleton: a single shared instance for the whole
 * app, and because the provider lives on the class instead of a module array, it drops out of the
 * bundle entirely if nothing injects it. Use a component/route provider instead only when you
 * genuinely want a fresh, scoped instance per subtree.
 *
 * State is exposed as a read model, never as the writable signal. `_watched` is private; consumers
 * get `ids` (an `asReadonly()` view) and the `count` derivation, so they can read and react but
 * can't reach in and mutate. Every change goes through a named method, which keeps the set of legal
 * transitions in one place.
 */
@Injectable({ providedIn: 'root' })
export class WatchlistService {
  // A real dependency, pulled with inject(). It reads cleaner than a constructor parameter and works
  // the same in a field initializer. The flag caps the list so the demo can show a "full" state.
  private readonly flags = inject(FEATURE_FLAGS);
  private readonly limit = this.flags.experimentalExport ? 50 : 8;

  private readonly _watched = signal<ReadonlySet<string>>(new Set());

  // The public read model. Components bind to this; it can't be reassigned from outside.
  readonly ids = this._watched.asReadonly();

  // A derived value, recomputed only when the set changes. Consumers never count by hand.
  readonly count = computed(() => this._watched().size);

  // True once the list hits its cap; the UI uses it to disable further adds.
  readonly isFull = computed(() => this._watched().size >= this.limit);

  has(id: string): boolean {
    return this._watched().has(id);
  }

  add(id: string): void {
    if (this.has(id) || this.isFull()) {
      return;
    }
    this._watched.update((set) => new Set(set).add(id));
  }

  remove(id: string): void {
    this._watched.update((set) => {
      const next = new Set(set);
      next.delete(id);
      return next;
    });
  }

  toggle(id: string): void {
    if (this.has(id)) {
      this.remove(id);
    } else {
      this.add(id);
    }
  }
}

Routing fundamentals

Routes map paths to lazily-loaded components; routerLink navigates without a full reload and routerLinkActive styles the current one; fragment and query params carry state in the URL; child routes nest. Every link on this page and the whole sidebar is this. The deep links here use fragment to land on a section.

Route guards

Guards answer three questions at three moments: CanMatch ("should this route even be considered?": false falls through to another route), CanActivate ("may we enter?": the auth gate, redirects with a UrlTree) and CanDeactivate ("may we leave?": the unsaved-changes prompt). Flip the demo session and try the links:

signed out role: guest

Signed out, the secure link redirects back here. As a guest the admin link doesn't match (the router falls through). In the draft editor, type then try to leave.

View source: three functional guardsguards.ts

Functional guards are just functions that run in the injection context, so inject() works directly, with no guard class to write. CanActivate returns a UrlTree to redirect; CanMatch skips the route (and its lazy chunk) entirely; CanDeactivate calls a method the component owns.

ts
import { Injectable, inject, signal } from '@angular/core';
import { CanActivateFn, CanDeactivateFn, CanMatchFn, Router } from '@angular/router';

/*
 * Functional guards: the modern shape. A guard is just a function that returns a boolean or a
 * UrlTree (redirect), and it runs inside the injection context, so `inject()` works directly.
 * Class guards (`implements CanActivate`) still work; a function is just less ceremony. The
 * three below cover the three questions the router asks at three different moments:
 *
 *   CanMatch:      "should this route even be considered?" (runs before the route is matched, so
 *                  a false here can fall through to a different route, the basis of role-based
 *                  routing and feature-flagged routes, and it skips lazy-loading the chunk).
 *   CanActivate:   "now that we've matched, may we enter?" (the classic auth gate; redirects).
 *   CanDeactivate: "may we leave?" (the unsaved-changes prompt; the guard the user feels most).
 */

/*
 * A trivially small "session" so the guards have something real to read. A signal, not a class
 * field, so the demo page can flip it and watch the guards react. In a real app this is an auth
 * service; the guard shape is identical.
 */
@Injectable({ providedIn: 'root' })
export class DemoSession {
  readonly signedIn = signal(false);
  readonly role = signal<'guest' | 'admin'>('guest');

  toggleSignedIn(): void {
    this.signedIn.update((v) => !v);
  }

  toggleRole(): void {
    this.role.update((r) => (r === 'admin' ? 'guest' : 'admin'));
  }
}

/*
 * CanActivate: gate entry on being signed in. Returning a UrlTree redirects instead of just
 * blocking: here, back to the fundamentals hub's guards section, so the user lands somewhere
 * sensible rather than on a dead navigation.
 */
export const requireSignIn: CanActivateFn = () => {
  const session = inject(DemoSession);
  const router = inject(Router);
  return session.signedIn() ? true : router.parseUrl('/fundamentals');
};

/*
 * CanMatch: only match the admin route when the role is admin. Because this runs at match time,
 * a non-admin doesn't get redirected. The route simply isn't there for them, and the router
 * moves on. `route` and `segments` are available if the decision depends on the path.
 */
export const requireAdmin: CanMatchFn = () => {
  const session = inject(DemoSession);
  return session.role() === 'admin';
};

/*
 * The contract a guarded component opts into. CanDeactivate is generic over the component, so
 * the guard can call a method the component owns. Keeping it an interface (not reaching into
 * component internals) means the guard stays decoupled: any component that can answer "is it
 * safe to leave?" can be guarded by it.
 */
export interface CanLeave {
  canLeave(): boolean;
}

/*
 * CanDeactivate: ask the component before navigating away. If it has unsaved work, confirm.
 * The `confirm()` is the demo stand-in for a real dialog; the guard's job is only to gate the
 * navigation on the answer, not to own the UI.
 */
export const confirmLeave: CanDeactivateFn<CanLeave> = (component) => {
  if (component.canLeave()) {
    return true;
  }
  return confirm('You have unsaved changes. Leave anyway?');
};

Resolvers

A resolver preloads a route's data before it activates, so the component renders with its data already in hand: no in-component spinner, no flash of empty shell. The trade-off: it delays the navigation until the data arrives, which is right for small must-have data and wrong for a slow call.

Open the resolved briefing →
View source: a functional resolverbriefing.resolver.ts

The router waits on the returned Observable to complete and hands the value to the component via the route snapshot, which is why the destination component has no loading branch to write.

ts
import { ResolveFn } from '@angular/router';
import { Observable, delay, of } from 'rxjs';

/*
 * A resolver preloads a route's data before the route activates, so the component renders with
 * its data already in hand: no in-component loading spinner, no flash of an empty shell. The
 * router waits on whatever the resolver returns (a value, a Promise, or an Observable that
 * completes) and hands the result to the activated component via the route snapshot.
 *
 * The trade-off worth naming: a resolver delays the navigation until the data arrives. That's
 * the right call for small, fast, must-have data (this briefing), and the wrong call for a slow
 * call that would leave the user staring at the old page. There, render and stream instead.
 */
export interface Briefing {
  readonly title: string;
  readonly generatedAt: string;
  readonly summary: string;
}

/*
 * The synthetic "fetch". `of(...).pipe(delay)` stands in for an HTTP call so the resolver has
 * something asynchronous to await. The point is the timing contract; the data source is a stand-in.
 */
export function loadBriefing(): Observable<Briefing> {
  return of<Briefing>({
    title: 'Daily desk briefing',
    generatedAt: new Date().toISOString(),
    summary: 'Resolved before the route activated. The component never rendered without it.',
  }).pipe(delay(300));
}

/*
 * Functional resolver: runs in the injection context, so a real one would `inject()` an HTTP
 * service here. The component reads the result with `inject(ActivatedRoute).snapshot.data`.
 */
export const briefingResolver: ResolveFn<Briefing> = () => loadBriefing();

HttpClient & interceptors

A typed HttpClient.get<Quote[]> through a chain of functional interceptors. The app's data is synthetic, so a fake-backend interceptor plays the server (the same technique you'd use against an API that doesn't exist yet), while auth, retry and error-mapping interceptors run against a real request/response cycle. "Load (with failures)" arms two transient 503s so the retry interceptor has something to recover from.

View source: interceptor chain, fake backend, typed servicehttp-demo.ts

Each interceptor is middleware wrapping next, like an onion: auth stamps the header on the way out, retry sits inside it, the fake backend is the core that responds. The service knows nothing about any of it; interceptors are wired once at the provider level.

ts
import { Injectable, inject } from '@angular/core';
import {
  HttpBackend,
  HttpClient,
  HttpErrorResponse,
  HttpEvent,
  HttpHandlerFn,
  HttpInterceptorFn,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Observable, defer, of, throwError } from 'rxjs';
import { catchError, delay, retry } from 'rxjs/operators';

/*
 * HttpClient fundamentals with a chain of functional interceptors over a fake backend. The app's
 * data is synthetic, so there's no server. Instead a class implementing `HttpBackend` plays the
 * server at the very bottom of the stack. That placement matters: the backend is the request's
 * single producer, below every interceptor, so when the retry interceptor resubscribes it
 * really re-runs the backend, exactly as a resubscribe would re-hit a real server. (An
 * interceptor-as-backend wouldn't: the chain is built once per request and doesn't re-execute on
 * a downstream retry.) Same technique you'd use to develop against an API that doesn't exist yet.
 *
 * The mental model that makes interceptors click: each one is middleware wrapping `next`. It can
 * touch the outgoing request before calling `next(req)`, and touch the incoming stream after. The
 * order you register them is the order requests pass through going out, and the reverse coming
 * back, like an onion. Auth (outermost) stamps the header first; retry sits inside it; the backend is
 * the core that finally responds.
 */

export interface Quote {
  readonly symbol: string;
  readonly price: number;
  readonly currency: string;
}

// A typed, immutable book of canned quotes the fake backend serves.
const QUOTES: readonly Quote[] = [
  { symbol: 'ACME', price: 184.22, currency: 'USD' },
  { symbol: 'GLOBEX', price: 57.9, currency: 'USD' },
  { symbol: 'INITECH', price: 312.45, currency: 'USD' },
];

export const QUOTES_URL = '/api/quotes';

/*
 * Outermost interceptor: stamp an Authorization header on every outgoing request. Requests are
 * immutable, so you `clone` to change them. Mutating `req` in place would be a no-op and a
 * source of confusing bugs. A real one reads a token from an auth service via `inject()`.
 */
export const authInterceptor: HttpInterceptorFn = (
  req: HttpRequest<unknown>,
  next: HttpHandlerFn,
): Observable<HttpEvent<unknown>> => {
  const authed = req.clone({ setHeaders: { Authorization: 'Bearer synthetic-demo-token' } });
  return next(authed);
};

/*
 * Retry transient failures with backoff, then map anything still failing into a clean, typed
 * Error so components never have to know about `HttpErrorResponse`. Splitting "retry" from "map"
 * keeps each concern legible: retry decides whether to try again, the catch decides what the rest
 * of the app sees on final failure.
 */
export const retryAndMapErrorsInterceptor: HttpInterceptorFn = (
  req: HttpRequest<unknown>,
  next: HttpHandlerFn,
): Observable<HttpEvent<unknown>> =>
  next(req).pipe(
    retry({ count: 2, delay: 200 }),
    catchError((err: HttpErrorResponse) =>
      throwError(() => new Error(`Request to ${req.url} failed (${err.status}).`)),
    ),
  );

/*
 * The fake backend: a real `HttpBackend`, the request's single producer. It answers QUOTES_URL,
 * models latency with `delay` and, armed by a `?fail=true` query param, fails a couple of
 * times with a 503 before succeeding, so the retry interceptor above has something to recover
 * from. `defer` is the key to making retry work: it re-reads the mutable failure counter on every
 * (re)subscription, so each retry attempt sees the decremented state rather than a value captured
 * once at request time.
 */
@Injectable()
export class FakeBackend implements HttpBackend {
  private failuresRemaining = 0;
  // A one-shot latch so a fail-run arms its failures once, not afresh on every retry attempt.
  private failRunActive = false;

  handle(req: HttpRequest<unknown>): Observable<HttpEvent<unknown>> {
    return defer(() => {
      if (req.params.get('fail') === 'true' && !this.failRunActive) {
        this.failuresRemaining = 2;
        this.failRunActive = true;
      }

      if (this.failuresRemaining > 0) {
        this.failuresRemaining--;
        return throwError(
          () =>
            new HttpErrorResponse({ status: 503, statusText: 'Service Unavailable', url: req.url }),
        ).pipe(delay(150));
      }

      // Reached a success: drop the latch so the next fail-run can arm afresh.
      this.failRunActive = false;
      return of(new HttpResponse<Quote[]>({ status: 200, body: [...QUOTES] })).pipe(delay(250));
    });
  }

  // Test-only: arm a fixed number of upcoming 503s to exhaust the retry budget on purpose.
  armFailures(count: number): void {
    this.failuresRemaining = count;
    this.failRunActive = true;
  }

  // Test-only reset between cases.
  reset(): void {
    this.failuresRemaining = 0;
    this.failRunActive = false;
  }
}

/*
 * A typed data service over HttpClient. The generic on `get<Quote[]>` is the contract: the
 * response body is typed all the way to the caller, so components consume `Quote[]`, not `any`.
 * The service knows nothing about interceptors or the backend. They're wired once at the
 * provider level and apply to every request this makes.
 */
@Injectable({ providedIn: 'root' })
export class QuotesService {
  private readonly http = inject(HttpClient);

  load(options: { fail?: boolean } = {}): Observable<Quote[]> {
    return this.http.get<Quote[]>(QUOTES_URL, {
      params: options.fail ? { fail: 'true' } : {},
    });
  }
}

Discriminated unions for component state

A request is idle, loading, loaded or failed: one of those, never two. Model it as a union tagged by status, where only the success member carries data and only the error member carries error, and the type rules out the states the screen can't draw. In the template, @let s = state() gives @switch a value to narrow, so s.data type-checks only inside the success case.

idle Idle: nothing requested yet.

Pick an outcome to start a request.

@default never(s); makes the switch exhaustive: add a member to the union and the build fails until it has a case. It names s because the switch reads a property of the union; there, a bare @default never; reports an error even with every case covered. The status line runs the same check in TypeScript, through a switch whose default hands the value to assertNever(value: never).

View source: the union and the loader

Each transition sets a whole new state, so there's never a stale error left over from the last request to clear by hand.

ts
import {
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  computed,
  inject,
  signal,
} from '@angular/core';
import { type Subscription, timer } from 'rxjs';
import { Alert, Button } from '@foo/ui';
import { type LoadState, describeState } from './load-state';

export interface ReportRow {
  readonly region: string;
  readonly orders: number;
}

export const REPORT_ROWS: readonly ReportRow[] = [
  { region: 'North', orders: 412 },
  { region: 'Coastal', orders: 287 },
  { region: 'Interior', orders: 153 },
];

// Long enough for a reader to see the loading case before it resolves.
export const LOAD_DELAY_MS = 1500;

/*
 * A loader whose whole state is one LoadState signal. `@let s = state()` gives the template a
 * name it can narrow: inside `@case ('success')` the type checker knows `s.data` exists, and
 * inside `@case ('error')` it knows `s.error` does. `@default never(s);` is the template's own
 * exhaustiveness check: it renders nothing, and the build fails if a status has no case. It names
 * `s` because the switch reads a property of the union; a bare `@default never;` reports an error
 * here even with every case covered (template-rules.spec.ts pins both behaviors).
 */
@Component({
  selector: 'foo-tagged-state',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Alert, Button],
  // Prettier 3.8 rewrites `@default never(s);` to `@default never;`, which doesn't compile here.
  // prettier-ignore
  template: `
    @let s = state();
    <div class="ts-controls">
      <button
        foo-button
        variant="primary"
        [disabled]="s.status === 'loading'"
        (click)="load('succeed')"
      >
        Load (succeeds)
      </button>
      <button
        foo-button
        variant="secondary"
        [disabled]="s.status === 'loading'"
        (click)="load('fail')"
      >
        Load (fails)
      </button>
      <button foo-button variant="secondary" (click)="reset()">Reset</button>
    </div>

    <p class="ts-status" role="status">
      <code class="ts-tag">{{ s.status }}</code> {{ summary() }}
    </p>

    <div class="ts-body">
      @switch (s.status) {
        @case ('idle') {
          <p class="ts-hint">Pick an outcome to start a request.</p>
        }
        @case ('loading') {
          <p class="ts-hint">Fetching the regional report…</p>
        }
        @case ('success') {
          <ul class="ts-rows" aria-label="Report rows">
            @for (row of s.data; track row.region) {
              <li>{{ row.region }}: {{ row.orders }} orders</li>
            }
          </ul>
        }
        @case ('error') {
          <foo-alert variant="danger" heading="Report failed">{{ s.error }}</foo-alert>
        }
        @default never(s);
      }
    </div>
  `,
  styles: `
    :host {
      display: grid;
      gap: var(--foo-space-3);
      margin-top: var(--foo-space-4);
      color: var(--foo-color-text);
    }
    .ts-controls {
      display: flex;
      flex-wrap: wrap;
      gap: var(--foo-space-3);
    }
    .ts-status,
    .ts-hint {
      margin: 0;
    }
    .ts-tag {
      font-weight: var(--foo-weight-semibold);
    }
    .ts-rows {
      margin: 0;
      padding-left: var(--foo-space-5);
      display: grid;
      gap: var(--foo-space-1);
    }
  `,
})
export class TaggedState {
  protected readonly state = signal<LoadState<readonly ReportRow[]>>({ status: 'idle' });
  protected readonly summary = computed(() => describeState(this.state()));

  private pending: Subscription | null = null;

  constructor() {
    inject(DestroyRef).onDestroy(() => this.pending?.unsubscribe());
  }

  // Each transition replaces the whole state, so there's no stale field from the last one to clear.
  protected load(outcome: 'succeed' | 'fail'): void {
    this.pending?.unsubscribe();
    this.state.set({ status: 'loading' });
    this.pending = timer(LOAD_DELAY_MS).subscribe(() =>
      this.state.set(
        outcome === 'succeed'
          ? { status: 'success', data: REPORT_ROWS }
          : { status: 'error', error: 'The report service timed out. Try again.' },
      ),
    );
  }

  protected reset(): void {
    this.pending?.unsubscribe();
    this.state.set({ status: 'idle' });
  }
}

The boolean-flags version it replaces happily compiles a value that's loading and failed at once, with stale rows on top. The same value typed as the union is a compile error, and the file keeps a @ts-expect-error on it, so the build fails if that ever stops being true.

View source: the boolean flags, for comparisonload-flags.ts

Nothing renders this file. It's compiled with the app so the comparison is real code, not a sketch.

ts
import type { LoadState } from './load-state';

/*
 * The shape LoadState replaces: three independent fields for one request. Nothing renders this;
 * it's here so the comparison is real code the build type-checks, not a sketch that could rot.
 */
export interface FlagsState<T> {
  readonly isLoading: boolean;
  readonly error: string | null;
  readonly data: T | null;
}

// Compiles without a murmur. Loading, failed and holding stale rows, all at once: which one wins
// is decided by whichever `@if` the template happens to check first.
export const contradictoryFlags: FlagsState<string[]> = {
  isLoading: true,
  error: 'Timed out',
  data: ['stale row'],
};

// The same contradiction against the union. If LoadState ever accepted it, this directive would
// go unused and the build would fail, so the claim can't quietly stop being true.
// @ts-expect-error: no member of LoadState has both a 'loading' status and an error
export const contradictoryUnion: LoadState<string[]> = { status: 'loading', error: 'Timed out' };

Lifecycle hooks

ngOnChanges runs when an input changes; ngOnInit runs once, after the first inputs are set; ngAfterViewInit once the component's own view is built; ngOnDestroy on teardown. For cleanup, the modern path is DestroyRef + takeUntilDestroyed(). It ties a subscription's life to the component's without a hand-written ngOnDestroy, which is exactly how the RxJS page keeps its streams from leaking.

The child below logs every hook it implements. Mount it and the log shows the order Angular calls them: the constructor, ngOnChanges (a signal input still reaches it), ngOnInit, then ngAfterViewInit. Change its input and ngOnChanges logs the old and new value; the init hooks don't run again. Unmount it and you get ngOnDestroy, then the DestroyRef.onDestroy callback, then the interval's finalize: takeUntilDestroyed() completed it, so the tick count freezes and the live-subscription count drops to zero.

No child mounted.

Ticks counted
0
Subscriptions alive
0

The log is empty. Mount the child to watch its hooks run.

View source: a child that logs its own lifecyclelifecycle-demo.ts

The log is provided by the parent, so it outlives the child: that's what lets the page show the subscription stopping after the component is gone.

ts
import {
  type AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  Injectable,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  type SimpleChanges,
  inject,
  input,
  signal,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { finalize, interval } from 'rxjs';
import { Button } from '@foo/ui';

export interface LogEntry {
  readonly id: number;
  readonly text: string;
}

/*
 * Outlives the child on purpose. It's provided by the parent, so the log, the tick count and the
 * live-subscription count are all still on screen after the child is gone: that's the only way to
 * show a reader that the child's subscription really stopped.
 */
@Injectable()
export class LifecycleLog {
  private nextId = 0;
  readonly entries = signal<readonly LogEntry[]>([]);
  readonly ticks = signal(0);
  readonly alive = signal(0);

  write(text: string): void {
    this.entries.update((list) => [...list, { id: this.nextId++, text }]);
  }

  clear(): void {
    this.entries.set([]);
  }
}

@Component({
  selector: 'foo-lifecycle-child',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p class="lc-child">
    Child mounted. Its input reads <strong>{{ label() }}</strong
    >.
  </p>`,
  styles: `
    .lc-child {
      margin: 0;
      padding: var(--foo-space-2) var(--foo-space-3);
      border: 1px dashed var(--foo-color-border-strong);
      border-radius: var(--foo-radius-md);
      color: var(--foo-color-text);
    }
  `,
})
export class LifecycleChild implements OnChanges, OnInit, AfterViewInit, OnDestroy {
  // A signal input still reaches ngOnChanges, so the hook can be shown without a decorator input.
  readonly label = input.required<string>();
  private readonly log = inject(LifecycleLog);

  constructor() {
    this.log.write('constructor');

    inject(DestroyRef).onDestroy(() => this.log.write('DestroyRef.onDestroy'));

    // No ngOnDestroy bookkeeping: takeUntilDestroyed() completes the stream when this component
    // is destroyed, and finalize is the proof, since it only runs once the subscription is gone.
    this.log.alive.update((n) => n + 1);
    interval(1000)
      .pipe(
        finalize(() => {
          this.log.alive.update((n) => n - 1);
          this.log.write('interval finalized (takeUntilDestroyed)');
        }),
        takeUntilDestroyed(),
      )
      .subscribe(() => this.log.ticks.update((n) => n + 1));
  }

  ngOnChanges(changes: SimpleChanges): void {
    const change = changes['label'];
    if (!change) return;
    this.log.write(
      change.firstChange
        ? `ngOnChanges: label = "${change.currentValue}" (first change)`
        : `ngOnChanges: label "${change.previousValue}" to "${change.currentValue}"`,
    );
  }

  ngOnInit(): void {
    this.log.write('ngOnInit');
  }

  ngAfterViewInit(): void {
    this.log.write('ngAfterViewInit');
  }

  ngOnDestroy(): void {
    this.log.write('ngOnDestroy');
  }
}

/*
 * The child starts unmounted, so its interval only ever starts in a reader's browser: a ticking
 * stream during server rendering would keep the prerender from settling.
 */
@Component({
  selector: 'foo-lifecycle-demo',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Button, LifecycleChild],
  providers: [LifecycleLog],
  template: `
    <div class="lc-controls">
      <button foo-button variant="primary" (click)="mounted.set(!mounted())">
        {{ mounted() ? 'Unmount child' : 'Mount child' }}
      </button>
      <button
        foo-button
        variant="secondary"
        [disabled]="!mounted()"
        (click)="revision.set(revision() + 1)"
      >
        Change input
      </button>
      <button foo-button variant="secondary" (click)="log.clear()">Clear log</button>
    </div>

    @if (mounted()) {
      <foo-lifecycle-child [label]="'Revision ' + revision()" />
    } @else {
      <p class="lc-empty">No child mounted.</p>
    }

    <dl class="lc-stats">
      <dt>Ticks counted</dt>
      <dd class="lc-ticks">{{ log.ticks() }}</dd>
      <dt>Subscriptions alive</dt>
      <dd class="lc-alive">{{ log.alive() }}</dd>
    </dl>

    <div class="lc-log" role="log" aria-label="Lifecycle log">
      @if (log.entries().length) {
        <ol class="lc-log__list">
          @for (entry of log.entries(); track entry.id) {
            <li>
              <code>{{ entry.text }}</code>
            </li>
          }
        </ol>
      } @else {
        <p class="lc-empty">The log is empty. Mount the child to watch its hooks run.</p>
      }
    </div>
  `,
  styles: `
    :host {
      display: grid;
      gap: var(--foo-space-3);
      margin-top: var(--foo-space-4);
      color: var(--foo-color-text);
    }
    .lc-controls {
      display: flex;
      flex-wrap: wrap;
      gap: var(--foo-space-3);
    }
    .lc-empty {
      margin: 0;
      color: var(--foo-color-text-muted);
    }
    .lc-stats {
      display: grid;
      grid-template-columns: max-content max-content;
      gap: var(--foo-space-1) var(--foo-space-4);
      margin: 0;
      font-variant-numeric: tabular-nums;
    }
    .lc-stats dd {
      margin: 0;
      font-weight: var(--foo-weight-semibold);
    }
    .lc-log {
      max-width: 40rem;
      padding: var(--foo-space-3);
      background: var(--foo-color-surface-sunken);
      border: 1px solid var(--foo-color-border);
      border-radius: var(--foo-radius-md);
    }
    .lc-log__list {
      margin: 0;
      padding-left: var(--foo-space-5);
      display: grid;
      gap: var(--foo-space-1);
    }
  `,
})
export class LifecycleDemo {
  protected readonly log = inject(LifecycleLog);
  protected readonly mounted = signal(false);
  protected readonly revision = signal(1);
}
See takeUntilDestroyed in the RxJS demos →

From NgModules to standalone

A standalone component, directive or pipe lists what its template uses in its own imports, so the scope sits next to the code instead of in a module somewhere else. It's been the default since Angular 19: declaring something in an NgModule now takes an explicit standalone: false.

Here is one small feature written both ways: a pipe, a component and the data they need. Both files are compiled and type-checked with the app, and a unit test renders each one, through its module and through bootstrapApplication, and checks they print the same list. The list below is the standalone version.

  • ACME +1.25%
  • GLOBEX -0.40%
  • INITECH 0.00%
View source: before, an NgModule

Every declaration opts out with standalone: false. The feature module declares, exports and provides; the root module exists only to bootstrap.

ts
/* eslint-disable @angular-eslint/prefer-standalone -- the NgModule "before" is the point of this file */
import {
  ChangeDetectionStrategy,
  Component,
  NgModule,
  Pipe,
  type PipeTransform,
  inject,
  provideZonelessChangeDetection,
} from '@angular/core';
import { BrowserModule, platformBrowser } from '@angular/platform-browser';
import { SAMPLE_TICKERS, TICKERS, formatSignedPercent } from './ticker-data';

/*
 * BEFORE: a small feature the NgModule way. Standalone is the default now, so every declaration
 * has to opt out with `standalone: false`, and the template's scope (what `signedPercent` means)
 * lives in the module, not next to the component that uses it.
 */
@Pipe({ name: 'signedPercent', standalone: false })
export class SignedPercentPipe implements PipeTransform {
  transform(value: number): string {
    return formatSignedPercent(value);
  }
}

@Component({
  selector: 'foo-ticker-list',
  standalone: false,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <ul class="ticker-list" aria-label="Tickers">
      @for (t of tickers; track t.symbol) {
        <li>
          <code>{{ t.symbol }}</code> {{ t.change | signedPercent }}
        </li>
      }
    </ul>
  `,
})
export class TickerList {
  protected readonly tickers = inject(TICKERS);
}

// The feature module: declares the pieces, exports the public one, provides its data.
@NgModule({
  declarations: [TickerList, SignedPercentPipe],
  exports: [TickerList],
  providers: [{ provide: TICKERS, useValue: SAMPLE_TICKERS }],
})
export class TickerModule {}

// The root module exists only to bootstrap.
@NgModule({
  imports: [BrowserModule, TickerModule],
  providers: [provideZonelessChangeDetection()],
  bootstrap: [TickerList],
})
export class TickerAppModule {}

// Wrapped in a function so the demo page never starts a second app; main.ts would call it.
export function bootstrapTickerApp() {
  return platformBrowser().bootstrapModule(TickerAppModule);
}
View source: after, standalone

The component imports its pipe, the module's providers became provideTickers(), and the root module became an ApplicationConfig.

ts
import {
  type ApplicationConfig,
  ChangeDetectionStrategy,
  Component,
  Pipe,
  type PipeTransform,
  type Provider,
  inject,
  provideZonelessChangeDetection,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { SAMPLE_TICKERS, TICKERS, formatSignedPercent } from './ticker-data';

/*
 * AFTER: the same feature with no NgModule. The pipe and component are standalone (the default,
 * so there's no flag to set), the component imports what its template uses, and the module's
 * providers become a provide function an app config or a route can call.
 */
@Pipe({ name: 'signedPercent' })
export class SignedPercentPipe implements PipeTransform {
  transform(value: number): string {
    return formatSignedPercent(value);
  }
}

@Component({
  selector: 'foo-ticker-list',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [SignedPercentPipe],
  template: `
    <ul class="ticker-list" aria-label="Tickers">
      @for (t of tickers; track t.symbol) {
        <li>
          <code>{{ t.symbol }}</code> {{ t.change | signedPercent }}
        </li>
      }
    </ul>
  `,
})
export class TickerList {
  protected readonly tickers = inject(TICKERS);
}

// What TickerModule's `providers` array turned into.
export function provideTickers(): Provider[] {
  return [{ provide: TICKERS, useValue: SAMPLE_TICKERS }];
}

// What TickerAppModule turned into: no class, just the providers.
export const tickerAppConfig: ApplicationConfig = {
  providers: [provideZonelessChangeDetection(), provideTickers()],
};

// Wrapped in a function so the demo page never starts a second app; main.ts would call it.
export function bootstrapTickerApp() {
  return bootstrapApplication(TickerList, tickerAppConfig);
}

Angular ships the migration as a schematic, ng generate @angular/core:standalone. It asks for a path and a mode, and the modes are meant to run in this order, with a build and a test run between each:

  1. Convert all components, directives and pipes to standalone (--mode=convert-to-standalone): drops standalone: false and adds each template's dependencies to its imports. It skips a module that bootstraps a component, since that's likely the root.
  2. Remove unnecessary NgModule classes (--mode=prune-ng-modules): deletes a module only when it has no declarations, providers or bootstrap components and no members, and leaves a TODO where it can't remove a reference. TickerModule provides TICKERS, so it survives this step; turning that provider into provideTickers() is the part you write by hand.
  3. Bootstrap the application using standalone APIs (--mode=standalone-bootstrap): swaps bootstrapModule for bootstrapApplication, deletes the root module and carries as much of its providers and imports as it can into the new bootstrap call.
View source: the test that holds both sides to the same outputticker.spec.ts

Both versions are rendered with TestBed and bootstrapped as real apps. If the before and after ever disagree, the build's test step says so.

ts
import { TestBed } from '@angular/core/testing';
import { ApplicationRef } from '@angular/core';
import * as before from './ticker.module';
import * as after from './ticker.standalone';
import { formatSignedPercent } from './ticker-data';

// The migration is only a refactor if both sides render the same thing.
const EXPECTED = ['ACME +1.25%', 'GLOBEX -0.40%', 'INITECH 0.00%'];

function rowsOf(root: Element): string[] {
  return Array.from(root.querySelectorAll('.ticker-list li')).map((li) =>
    (li.textContent ?? '').replace(/\s+/g, ' ').trim(),
  );
}

describe('NgModule to standalone: the ticker feature', () => {
  it('renders the NgModule version through its feature module', () => {
    TestBed.configureTestingModule({ imports: [before.TickerModule] });
    const fixture = TestBed.createComponent(before.TickerList);
    fixture.detectChanges();
    expect(rowsOf(fixture.nativeElement)).toEqual(EXPECTED);
  });

  it('renders the standalone version with its provide function', () => {
    TestBed.configureTestingModule({ providers: [after.provideTickers()] });
    const fixture = TestBed.createComponent(after.TickerList);
    fixture.detectChanges();
    expect(rowsOf(fixture.nativeElement)).toEqual(EXPECTED);
  });

  describe('bootstrapped as real apps', () => {
    let host: HTMLElement;
    let app: ApplicationRef | null = null;

    beforeEach(() => {
      host = document.createElement('foo-ticker-list');
      document.body.appendChild(host);
    });

    afterEach(() => {
      app?.destroy();
      app = null;
      host.remove();
    });

    it('bootstrapModule(TickerAppModule) renders the list', async () => {
      const moduleRef = await before.bootstrapTickerApp();
      app = moduleRef.injector.get(ApplicationRef);
      await app.whenStable();
      expect(rowsOf(document.body)).toEqual(EXPECTED);
    });

    it('bootstrapApplication(TickerList, tickerAppConfig) renders the same list', async () => {
      app = await after.bootstrapTickerApp();
      await app.whenStable();
      expect(rowsOf(document.body)).toEqual(EXPECTED);
    });
  });

  it('formats the sign the same way for both', () => {
    expect(new before.SignedPercentPipe().transform(-1)).toBe(formatSignedPercent(-1));
    expect(new after.SignedPercentPipe().transform(2.5)).toBe('+2.50%');
  });
});