Angular · Lesson 2

Signals

Angular's reactive state. `signal`, `computed` and `effect`, equality and immutable updates, `untracked`, `linkedSignal`, `resource`, how glitch-free derivation works, and when to use signals or RxJS.

11 min read

In short

  • signal holds state; read it by calling it
  • Change it with set or update, and replace, never mutate
  • computed derives state: lazy, cached and glitch-free
  • effect is for side effects, not for deriving state
  • Expose read-only signals from services

Signals are how modern Angular holds state. A signal is a value that knows who reads it: when it changes, the templates, computed values and effects that read it are updated, and nothing else is. That precision is also what lets Angular skip checking components whose data didn't change (see the Change detection topic).

You'll use signals for component state, for inputs (input() returns one), for derived values, and in services that act as small stores. This lesson covers the API and, more importantly, the rules behind it: what counts as a change, when things recompute, and when effects run.

Blocks that import @angular/core can't run in the lab. The plain TypeScript blocks can. The React & Angular patterns topic in the TypeScript track has an exercise that builds signal/computed/effect from scratch; the exercises here go further: equality, immutable updates, linkedSignal, toSignal, a version-based computed engine and resource.

signal: state you can read and write

import { Injectable, computed, signal } from '@angular/core';

export interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
}

@Injectable({ providedIn: 'root' })
export class CartStore {
  private readonly _items = signal<CartItem[]>([]);      // WritableSignal<CartItem[]>
  readonly items = this._items.asReadonly();              // Signal<CartItem[]>: no set/update outside
  readonly count = computed(() => this._items().reduce((n, i) => n + i.quantity, 0));
  readonly total = computed(() => this._items().reduce((sum, i) => sum + i.price * i.quantity, 0));

  add(item: CartItem): void {
    this._items.update((items) => [...items, item]);
  }

  remove(id: string): void {
    this._items.update((items) => items.filter((i) => i.id !== id));
  }
}
  • Read by calling it: count(), and in templates {{ store.count() }}.
  • Write with set(value) or update(fn). Only WritableSignal has them.
  • Give the type when the initial value doesn't show it: signal<User | null>(null).
  • Expose read-only signals from services (asReadonly()) and keep writes in methods. Then every change to the state goes through code you can find and test. This "signal store in a service" is the most common state pattern in new Angular code. NgRx's @ngrx/signals (SignalStore) is a library version of it.

What counts as a change: equality

set compares the new value with the current one using Object.is. If they're equal, nothing happens: no computed recomputes, no effect runs, no template updates. For objects and arrays, Object.is compares references:

▶ Try
const items = ['tea'];
const same = items;
same.push('cake');                                  // mutation: still the same array
console.log('mutated, same reference?', Object.is(items, same));          // true: a signal would see "no change"

const next = [...items, 'scones'];                  // immutable update: a new array
console.log('copied, same reference?', Object.is(items, next));           // false: a change

console.log('NaN vs NaN:', Object.is(NaN, NaN), ' 0 vs -0:', Object.is(0, -0));

So the rule for signals (and for OnPush, pure pipes and @for tracking) is the same: never mutate state, replace it. items.update((list) => [...list, x]), not items().push(x). Exercise 2 practises this.

You can pass your own equality: signal(user, { equal: (a, b) => a.id === b.id }). If equal returns true, the new value is dropped and the old one is kept. That's useful for a computed that builds a new array every time but often with the same contents, and dangerous for state: with the equal above, setting the same user with a new name is silently ignored. Exercise 1 builds signal with equal.

computed: derived state

import { computed, signal } from '@angular/core';

const showDone = signal(false);
const todos = signal([{ id: 1, title: 'Write tests', done: true }]);

const visible = computed(() => (showDone() ? todos() : todos().filter((t) => !t.done)));
const summary = computed(() => `${visible().length} of ${todos().length}`);
  • Lazy: the function doesn't run until something reads the computed.
  • Memoized: reading it again returns the cached value, as long as nothing it read has changed.
  • Dynamic dependencies: the dependencies are whatever it read on its last run. While showDone() is true, the branch doesn't read anything else, but it's re-collected on every run, so it's always right.
  • Equality cutoff: if a computed recomputes to an Object.is-equal value, things that read it don't recompute.
  • Read-only, and no side effects. Writing a signal inside a computed throws. If the function throws, the error is cached and rethrown on every read until a dependency changes.

computed replaces most of what ngOnChanges, BehaviorSubject + combineLatest + map, and getters with heavy logic used to do.

Glitch-free: push, then pull

firstName ─┐
           ├─> fullName ─┐
lastName ──┘             ├─> template
             initials ───┘   (reads fullName and initials)

When you set a signal, Angular does two things, in two phases:

  1. Push (cheap): it walks the graph and marks everything downstream as maybe stale. Nothing is computed yet.
  2. Pull (exact): when something reads a stale computed (the template during change detection, or an effect), the computed asks its dependencies whether their version really changed, refreshing them first if they're stale themselves. Only then does it recompute.

Because values are only computed on demand, in dependency order, a reader never sees a mix of old and new values (a glitch). Compare RxJS's combineLatest, which emits once per source and can show Bo Lee between Ann Lee and Bo Ng (see the RxJS & Observables topic). And because each producer has a version number, "did anything change?" is a number comparison, whatever the value is. Exercise 5 builds this engine.

effect: side effects

import { Component, effect, inject, signal, untracked } from '@angular/core';

@Component({ selector: 'app-editor', template: '' })
export class Editor {
  private readonly analytics = inject(Analytics);
  readonly draft = signal(localStorage.getItem('draft') ?? '');
  readonly docId = signal('doc-1');

  constructor() {
    // Runs once, then again whenever draft() changes.
    effect(() => localStorage.setItem('draft', this.draft()));

    // onCleanup runs before the next run and when the component is destroyed.
    effect((onCleanup) => {
      const id = this.docId();
      const timer = setInterval(() => this.analytics.ping(id), 30_000);
      onCleanup(() => clearInterval(timer));
    });

    // untracked: read a signal without depending on it.
    effect(() => {
      const id = this.docId();                                  // tracked: re-run when the document changes
      untracked(() => this.analytics.track('opened', id, this.draft().length)); // draft() not tracked
    });
  }
}
  • An effect runs at least once, then again when a signal it read changes.
  • Effects are scheduled, not synchronous. Setting a signal doesn't run an effect right away. Effects created in a component run during change detection, just before that component is checked. Effects created in root services run before any component is checked. So three set calls in a row cause one run, which sees the final values.
  • effect() needs an injection context (a constructor or field initializer), or { injector }. It's destroyed with its component, or by calling destroy() on the EffectRef it returns.
  • Use effects to sync signals to the outside world: storage, logging, analytics, a third-party widget, the DOM. (For DOM work after rendering, afterRenderEffect exists.)
  • Don't use effects to derive state. effect(() => this.total.set(this.a() + this.b())) causes an extra round of updates and ordering bugs. That's computed(() => this.a() + this.b()). Writing signals inside effects is allowed, but it's usually a smell.

untracked

untracked(fn) runs fn without recording dependencies. Use it in effects for values you need but don't want to re-run for (the user's locale, a logger's config), and when calling code that might read signals you don't know about (a service method).

linkedSignal: derived state you can still edit

Sometimes a value is derived, and the user can change it: the selected shipping option defaults to the first one, the user picks another, and when the list of options changes it resets. That's linkedSignal:

import { Component, input, linkedSignal } from '@angular/core';

interface ShippingOption {
  id: string;
  label: string;
}

@Component({ selector: 'app-shipping', template: '' })
export class Shipping {
  readonly options = input.required<ShippingOption[]>();
  readonly filter = input('');

  // Short form: reset to the first option whenever the options change.
  readonly selected = linkedSignal(() => this.options()[0]);

  // Long form: keep the user's choice if it's still in the new list.
  readonly kept = linkedSignal<ShippingOption[], ShippingOption | undefined>({
    source: this.options,
    computation: (options, previous) => options.find((o) => o.id === previous?.value?.id) ?? options[0],
  });

  // Reset to page 1 whenever the filter changes; the user can still page.
  readonly page = linkedSignal({ source: this.filter, computation: () => 1 });

  choose(option: ShippingOption): void {
    this.selected.set(option);
  }
}

It's a WritableSignal: set and update work, and the value they set stays until the source changes. Then the computation runs again, with previous holding the old source and value. Before linkedSignal, this needed an effect that wrote to a signal, which is exactly the pattern to avoid. Exercise 3 builds it.

resource: async data as signals

import { Component, input, resource } from '@angular/core';

interface User {
  id: string;
  name: string;
}

@Component({
  selector: 'app-user-card',
  template: `
    @if (user.hasValue()) {
      <h2>{{ user.value().name }}</h2>
    } @else if (user.error()) {
      <p>Could not load the user. <button (click)="user.reload()">Retry</button></p>
    } @else if (user.isLoading()) {
      <app-spinner />
    }
  `,
})
export class UserCard {
  readonly userId = input.required<string>();

  readonly user = resource({
    params: () => ({ id: this.userId() }),           // undefined here means "don't load" (status 'idle')
    loader: async ({ params, abortSignal }) => {
      const response = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return (await response.json()) as User;
    },
  });
}
  • When params changes, the previous load is aborted (abortSignal) and a new one starts, like switchMap.
  • status() is 'idle', 'loading' (params changed), 'reloading' (reload() was called), 'resolved', 'error' or 'local' (you called set/update). isLoading() covers both loading states.
  • value() is undefined (or the defaultValue option) while loading after a params change, keeps the old value while reloading, and throws in the error state. That's why templates check hasValue() first.
  • httpResource(() => `/api/users/${this.userId()}`) does the same with HttpClient, so interceptors apply. rxResource({ params, stream }) takes a loader that returns an Observable.
  • resource and rxResource (since Angular 19) and httpResource (since 19.2) were experimental until Angular 21. They're stable since Angular 22, so an older codebase may not use them yet. Exercise 6 builds the state machine.

Signals and RxJS

Rule of thumb (from the RxJS & Observables topic): state ("what's the current value?") belongs in signals. Events over time ("what happens when, in what order, and what gets cancelled?") belong in RxJS. The bridges live in @angular/core/rxjs-interop:

import { Component, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';

@Component({ selector: 'app-search', template: '' })
export class Search {
  private readonly api = inject(ProductApi);
  readonly query = signal('');

  readonly results = toSignal(
    toObservable(this.query).pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((q) => this.api.search(q)),
    ),
    { initialValue: [] },
  );
}
  • toSignal(obs$) subscribes immediately and unsubscribes when the component is destroyed. Before the first value it returns initialValue (default undefined). { requireSync: true } is for sources that emit right away (BehaviorSubject, startWith) and drops undefined from the type. If the Observable errors, reading the signal throws. Exercise 4 builds it.
  • toObservable(sig) emits the signal's value through an effect, so emissions are asynchronous and only the latest value of a burst gets through. Don't use it to observe every single set.
  • Keep using RxJS for debouncing, cancellation, retries, websockets and combining event streams. Convert to a signal at the end, for the template.

Common mistakes

  • Mutating an array or object in a signal. Nothing updates. Replace it.
  • Deriving state in an effect instead of computed or linkedSignal.
  • Reading signals after an await inside an effect or computed. Tracking is synchronous, so those reads aren't dependencies.
  • Forgetting the parentheses: @if (isOpen) tests the signal function, which is always truthy. With strictTemplates, the compiler warns about uninvoked signals in interpolations, bindings and @if/@switch conditions (NG8109). It's only a warning, though, and it doesn't catch every expression a signal can appear in.
  • computed that returns a new object every time (computed(() => ({ ...a(), ...b() }))) is always "changed", so everything downstream recomputes. Return primitives or stable references, or pass equal.
  • Creating an effect outside an injection context (in ngOnInit, or a callback): NG0203. Create it in the constructor, or pass { injector }.

How it looks in a real codebase

Side note
  • Components: inputs are signals, local UI state is signal, everything derived is computed, and the template reads them. With OnPush (the default since Angular 22) or zoneless change detection, Angular refreshes only the components whose signals changed.
  • Services: a private writable signal, public read-only signals and computed selectors, and methods for every change. RxJS stays at the edges (HTTP, websockets), converted with toSignal or resource.
  • Tests: reading a signal is synchronous, so most tests are just store.add(x); expect(store.count()).toBe(1). Effects are scheduled, so a test runs them with TestBed.tick() (older versions: TestBed.flushEffects()).
ReactAngular signals
useStatesignal (in a component or a service)
useMemo(fn, deps)computed(fn), with dependencies tracked automatically
useEffect(fn, deps)effect(fn), with dependencies tracked automatically
state reset with a key, or "derive state from props"linkedSignal
TanStack Query useQueryresource / httpResource

The exercises

  1. A writable signal: set, update, asReadonly and a custom equal, and what "equal" really means.
  2. Immutable updates: updater functions for signal.update that never mutate and keep untouched items' identity.
  3. linkedSignal: reset on source changes, keep local edits otherwise, with previous and equal.
  4. toSignal: subscribe, initial values, requireSync, errors and cleanup, with real RxJS.
  5. A computed engine: lazy, memoized, versioned and glitch-free computed, with error caching and cycle detection.
  6. resource: the loading state machine with params, abort, reload, local values and errors.

Practise this lesson

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

Open in the app