Sub topic 3
Deriving State with computed()
This chapter assumes you know TypeScript arrow functions and generics, can build an Angular component with a template, and have created writable signals with signal(), set(), and update().
Many values in a component are not independent state. They follow from other state. A total price comes from a price and a quantity, and a filtered list comes from a list and a search term. If you store these as separate writable signals, you have to keep them in sync by hand. computed() lets you declare the relationship once so that Angular keeps the value current for you.
The Basic Pattern
A computed signal is a read-only signal whose value comes from a derivation function. Any signal you read inside that function becomes a dependency.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ count() }} (double: {{ double() }})</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`,
})
export class CounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
increment() {
this.count.update(c => c + 1);
}
reset() {
this.count.set(0);
}
}You read double() the same way you read any signal, but it has no set() or update(). The only way to change it is to change count.
Lazy Evaluation and Memoization
A computed signal does no work until something reads it. After the first read, it caches the result. It runs the function again only when a dependency has changed and someone reads the value again.
import { computed, signal } from '@angular/core';
const price = signal(20);
const qty = signal(3);
let runs = 0;
const total = computed(() => {
runs++;
return price() * qty();
});
console.log(runs); // 0: nothing has read total yet
console.log(total()); // 60
console.log(total()); // 60, served from the cache
console.log(runs); // 1
qty.set(4);
console.log(runs); // 1: marked stale, not recomputed yet
console.log(total()); // 80
console.log(runs); // 2This behavior means expensive derivations, such as filtering or sorting a large array, are cheap to read many times in a template.
Dynamic Dependencies
Angular records dependencies on each run, not by analyzing your code. Only the signals actually read during the most recent run count as dependencies.
import { computed, signal } from '@angular/core';
const showDetails = signal(false);
const details = signal('Shipping in 2 days');
const summary = computed(() =>
showDetails() ? details() : 'Details hidden'
);While showDetails is false, the branch that reads details() never runs. Changes to details therefore do not mark summary as stale. Once showDetails becomes true, details is picked up as a dependency on the next run.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Calling `set()` on a signal inside `computed()` | Angular throws an error | Move writes to event handlers or `effect()` |
| Side effects such as HTTP calls or logging in the derivation | They run unpredictably, or not at all, because evaluation is lazy | Keep derivations pure |
| Mutating an array in place with `push()` | The source signal does not notify, so the computed value stays stale | Replace it: `update(a => [...a, x])` |
| Reading a plain class property instead of a signal | No dependency is recorded, so the value never updates | Store that value in a signal |
Exercise
A component has items = signal<string[]>([]) and count = computed(() => this.items().length). A method runs this.items().push('a'), but count() still shows 0. Why, and how do you fix it?
Show answer
push() mutates the existing array, and the signal never learns that anything changed, so count is never marked stale. Replace the array instead: this.items.update(list => [...list, 'a']).
Exercise
In the price and quantity example, you call price.set(25) three times and never read total. How many times does the derivation function run?
Show answer
Zero. A computed signal only recomputes when it is read. It runs once on the next read of total().