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.
In short
signalholds state; read it by calling it- Change it with
setorupdate, and replace, never mutate computedderives state: lazy, cached and glitch-freeeffectis 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)orupdate(fn). OnlyWritableSignalhas 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:
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()istrue, 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
computedthrows. 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:
- Push (cheap): it walks the graph and marks everything downstream as maybe stale. Nothing is computed yet.
- 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
setcalls 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 callingdestroy()on theEffectRefit returns.- Use effects to sync signals to the outside world: storage, logging, analytics, a third-party widget, the DOM.
(For DOM work after rendering,
afterRenderEffectexists.) - 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'scomputed(() => 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
paramschanges, the previous load is aborted (abortSignal) and a new one starts, likeswitchMap. status()is'idle','loading'(params changed),'reloading'(reload()was called),'resolved','error'or'local'(you calledset/update).isLoading()covers both loading states.value()isundefined(or thedefaultValueoption) while loading after a params change, keeps the old value while reloading, and throws in the error state. That's why templates checkhasValue()first.httpResource(() => `/api/users/${this.userId()}`)does the same withHttpClient, so interceptors apply.rxResource({ params, stream })takes a loader that returns an Observable.resourceandrxResource(since Angular 19) andhttpResource(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 returnsinitialValue(defaultundefined).{ requireSync: true }is for sources that emit right away (BehaviorSubject,startWith) and dropsundefinedfrom 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 singleset.- 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
computedorlinkedSignal. - Reading signals after an
awaitinside 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. WithstrictTemplates, the compiler warns about uninvoked signals in interpolations, bindings and@if/@switchconditions (NG8109). It's only a warning, though, and it doesn't catch every expression a signal can appear in. computedthat returns a new object every time (computed(() => ({ ...a(), ...b() }))) is always "changed", so everything downstream recomputes. Return primitives or stable references, or passequal.- 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 iscomputed, and the template reads them. WithOnPush(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
computedselectors, and methods for every change. RxJS stays at the edges (HTTP, websockets), converted withtoSignalorresource. - 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 withTestBed.tick()(older versions:TestBed.flushEffects()).
| React | Angular signals |
|---|---|
useState | signal (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 useQuery | resource / httpResource |
The exercises
- A writable signal:
set,update,asReadonlyand a customequal, and what "equal" really means. - Immutable updates: updater functions for
signal.updatethat never mutate and keep untouched items' identity. - linkedSignal: reset on source changes, keep local edits otherwise, with
previousandequal. - toSignal: subscribe, initial values,
requireSync, errors and cleanup, with real RxJS. - A computed engine: lazy, memoized, versioned and glitch-free
computed, with error caching and cycle detection. - 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