Sub topic 11
Reactive State with Signals
This chapter assumes you can build a standalone component and write a template with interpolation, property binding, event binding, @if, and @for. Earlier chapters covered all of those. Here you will learn how Angular tracks changing state with signals, how to derive values with computed, how to run side effects with effect, and which mistakes show up most often in practice.
Why Angular Needs a Reactive Primitive
A template shows data held by a component. When that data changes, Angular has to work out which parts of the page to update. For most of Angular's history, it did this by running change detection over the component tree and comparing the current value of each template expression with its previous value. That approach works without any special effort from you, but Angular cannot tell exactly what changed, so it checks a lot of things that did not change.
A signal is a wrapper around a value that tells its consumers when the value changes. When a template reads a signal, Angular records that dependency. When the signal is updated, Angular knows which views depend on it and marks only those for refresh. The result is more predictable updates, and it allows applications to drop Zone.js-based change detection completely if they want to.
| Approach | How Angular finds changes | Typical cost |
|---|---|---|
| Plain class fields | Re-checks template expressions during change detection | Checks many bindings that did not change |
| Signals | Signals notify their consumers directly | Updates only views that read the changed signal |
Writable Signals
You create a writable signal with signal(), giving it an initial value. You read the value by calling the signal like a function. You change it with set() or update().
import { signal } from '@angular/core';
const count = signal(0); // WritableSignal<number>
console.log(count()); // 0
count.set(5); // replace the value
count.update((c) => c + 1); // compute the new value from the old one
console.log(count()); // 6Use set() when the new value doesn't depend on the old one, such as resetting a form field. Use update() when it does, such as incrementing a counter or appending to a list.
TypeScript infers the signal's type from the initial value. When the initial value is too narrow, give the type explicitly:
import { signal } from '@angular/core';
interface User {
id: number;
name: string;
}
const currentUser = signal<User | null>(null);
currentUser.set({ id: 1, name: 'Ada' });Computed Signals
A computed signal derives its value from other signals. You pass computed() a function. Angular runs that function, records every signal it reads, and caches the result.
import { computed, signal } from '@angular/core';
const price = signal(20);
const quantity = signal(3);
const total = computed(() => price() * quantity());
console.log(total()); // 60
quantity.set(4);
console.log(total()); // 80Computed signals have three properties you can rely on:
- Lazy. The function does not run until something reads
total(). - Memoized. Reading
total()many times without a dependency change returns the cached value and does not run the function again. - Read-only. A computed signal has no
set()orupdate(). To change it, you change its inputs.
Dependencies are tracked dynamically. Only the signals read during the most recent run count as dependencies:
import { computed, signal } from '@angular/core';
const showDetails = signal(false);
const details = signal('Full description');
const label = computed(() => (showDetails() ? details() : 'Hidden'));While showDetails() is false, the function never reads details, so changes to details do not cause a recomputation. Once showDetails becomes true, details becomes a dependency.
How Signals Connect to the Template
The diagram below shows the dependency graph for the shopping cart component that comes next. Writable signals sit at the edges of the graph, computed signals sit in the middle, and the template and effects consume them.
When items changes, Angular marks subtotal and total as stale and schedules the template for refresh. The values are recomputed only when something reads them.
A Worked Example: A Shopping Cart
This standalone component uses all three signal APIs. Add it to a project generated with ng new and render <app-cart /> from the root component.
import { Component, computed, effect, signal } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
interface CartItem {
id: number;
name: string;
price: number;
qty: number;
}
@Component({
selector: 'app-cart',
imports: [CurrencyPipe],
template: `
@for (item of items(); track item.id) {
<div>
{{ item.name }} × {{ item.qty }}
<button (click)="changeQty(item.id, 1)">+</button>
<button (click)="changeQty(item.id, -1)">-</button>
</div>
} @empty {
<p>Your cart is empty.</p>
}
<p>Subtotal: {{ subtotal() | currency }}</p>
<p>Total (incl. tax): {{ total() | currency }}</p>
<button (click)="addSample()">Add sample item</button>
`,
})
export class Cart {
items = signal<CartItem[]>([]);
taxRate = signal(0.2);
subtotal = computed(() =>
this.items().reduce((sum, i) => sum + i.price * i.qty, 0),
);
total = computed(() => this.subtotal() * (1 + this.taxRate()));
private nextId = 1;
constructor() {
effect(() => {
console.log(`Cart total is now ${this.total().toFixed(2)}`);
});
}
addSample() {
const id = this.nextId++;
this.items.update((list) => [
...list,
{ id, name: `Item ${id}`, price: 9.99, qty: 1 },
]);
}
changeQty(id: number, delta: number) {
this.items.update((list) =>
list
.map((i) => (i.id === id ? { ...i, qty: i.qty + delta } : i))
.filter((i) => i.qty > 0),
);
}
}Every update() call returns a new array and new item objects. That detail matters, as the section on common errors explains.
Effects
An effect is a function that runs once, then runs again whenever a signal it read changes. Effects suit work that has to happen outside the signal graph: logging, saving to localStorage, or calling a third-party library that has no knowledge of Angular.
import { Component, effect, signal } from '@angular/core';
@Component({
selector: 'app-theme-toggle',
template: `<button (click)="toggle()">Theme: {{ theme() }}</button>`,
})
export class ThemeToggle {
theme = signal<'light' | 'dark'>(
(localStorage.getItem('theme') as 'light' | 'dark') ?? 'light',
);
constructor() {
effect(() => {
localStorage.setItem('theme', this.theme());
document.body.dataset['theme'] = this.theme();
});
}
toggle() {
this.theme.update((t) => (t === 'light' ? 'dark' : 'light'));
}
}Effects run asynchronously as part of Angular's change detection, so they never run in the middle of your own code. Several quick changes to theme in a row lead to a single effect run with the latest value. An effect created in a component is destroyed automatically when the component is destroyed.
Don't use an effect to copy one signal into another. If a value can be derived, use computed. An effect that sets other signals adds an extra change-detection pass and makes the data flow harder to follow.
Reading Without Tracking
Sometimes a computed signal or an effect has to read a signal without depending on it. untracked() lets you do that:
import { Component, effect, signal, untracked } from '@angular/core';
@Component({
selector: 'app-search-log',
template: `<input (input)="query.set($any($event.target).value)" />`,
})
export class SearchLog {
query = signal('');
userId = signal('guest');
constructor() {
effect(() => {
const q = this.query();
// Re-run only when query changes, not when userId changes.
const user = untracked(() => this.userId());
console.log(`${user} searched for "${q}"`);
});
}
}Common Errors and Gotchas
Forgetting the parentheses
{{ count }} in a template renders the signal function, not its value. Write {{ count() }}. The same applies in TypeScript: if (this.items.length) checks the length of a function's parameter list, which is not what you meant. Always call the signal.
Mutating values in place
Signals compare the old and new value with Object.is by default. The code below changes the array, but the signal never notifies anyone:
// Wrong: same array reference, so consumers are not notified
this.items().push(newItem);
// Also wrong: update returns the same reference
this.items.update((list) => {
list.push(newItem);
return list;
});
// Right: return a new array
this.items.update((list) => [...list, newItem]);Treat objects and arrays held in signals as immutable. If you have a real need to customize this, signal() and computed() accept an equal option, for example signal(initial, { equal: (a, b) => a.id === b.id }).
Writing to signals inside computed
The function passed to computed must not have side effects. Calling set() or update() inside it throws an error. Move the write into an event handler or, if there is no other option, an effect.
Expecting synchronous effects
Code that sets a signal and then immediately checks whether the effect ran will see that it hasn't run yet. In unit tests, call TestBed.tick() (or fixture.detectChanges()) to flush pending effects.
Exposing writable state
When a service holds state, keep the writable signal private and expose a read-only view so that consumers cannot change it directly:
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterStore {
private readonly _count = signal(0);
readonly count = this._count.asReadonly();
increment() {
this._count.update((c) => c + 1);
}
}Choosing the Right Tool
| Need | Use |
|---|---|
| State that your code changes directly | `signal()` |
| A value derived from other state | `computed()` |
| Synchronizing with the DOM, storage, or logging | `effect()` |
| Reading a signal without creating a dependency | `untracked()` |
| Sharing state across components | A signal in a service, exposed with `asReadonly()` |
Exercise
A component has tags = signal<string[]>([]). A method runs this.tags().push('new'), but the template showing tags().length does not update. Explain why, and rewrite the method so that it works.
Show answer
push changes the existing array in place, so the signal still holds the same reference. Signals compare values with Object.is, and no set or update was called, so consumers are never notified. Replace the method body with this.tags.update((list) => [...list, 'new']);, which returns a new array and triggers the update.
Exercise
You need a fullName value built from the firstName and lastName signals. A teammate writes an effect that calls this.fullName.set(...) whenever either one changes. What should you use instead, and why?
Show answer
Use fullName = computed(() => ${this.firstName()} ${this.lastName()}). A computed signal is lazy, memoized, and read-only. It cannot fall out of sync with its sources, and it avoids the extra change-detection pass that an effect writing to another signal causes. Keep effects for side effects outside the signal graph.
Exercise
In the Cart component, which signals does total depend on, and does adding an item cause total's function to run if nothing reads total()?
Show answer
total reads subtotal and taxRate, and subtotal depends on items. Adding an item marks subtotal and total as stale but does not run their functions. Computed signals are lazy, so they recompute only when read. In the real component, the template and the effect do read total(), so it is recomputed during the next change detection.