Sub topic 2
Deriving state with computed()
This chapter assumes you know basic TypeScript, can build an Angular component with a template, and have used signal() with set() and update(). You also need a high-level idea of change detection.
Why derive state
Suppose a component holds a price and a quantity. The total is not new information. It follows from the other two values. If you store it in a third writable signal, you must update it every time either source changes, and sooner or later you will forget.
A computed signal solves this. computed() takes a function and returns a read-only signal. Its value is whatever the function returns, and Angular keeps it consistent with the signals the function reads.
Your first computed signal
import { signal, computed } from '@angular/core';
const price = signal(10);
const quantity = signal(2);
const total = computed(() => price() * quantity());
console.log(total()); // 20
quantity.set(3);
console.log(total()); // 30You read a computed signal by calling it, like any other signal. Inside the function, calling price() and quantity() tells Angular that total depends on both. When quantity changes, total is marked as stale.
A computed signal has no set() or update(). Its type is Signal<T>, not WritableSignal<T>, so the compiler rejects an attempt to write to it. The only way to change it is to change the signals it reads.
In a template you call it the same way: {{ total() }}. Angular tracks the read there too, so the view updates when the value changes.
Lazy and cached
A computed function does not run when you create the computed signal. It runs the first time something reads it. After that, Angular stores the result and returns the stored value on later reads without running the function again.
When a dependency changes, Angular does not recalculate immediately. It marks the computed value as dirty. The function runs again only on the next read.
The diagram below shows this sequence.
Two consequences follow:
- Expensive calculations cost nothing until someone needs the result.
- Reading the same computed value ten times in a template runs the function once, as long as its dependencies stay the same.
Because of this, keep the function pure. It should read signals and return a value. It should not log, call a server or write to other signals, since you cannot know when, or how often, it will run.
Dependencies are found at run time
Angular does not analyze your code to find dependencies. It watches which signals are actually read during the most recent run of the function. Branches that are skipped contribute no dependencies.
import { signal, computed } from '@angular/core';
const showDetails = signal(false);
const name = signal('Ada');
const details = signal('Mathematician');
const label = computed(() =>
showDetails() ? `${name()} - ${details()}` : name()
);
console.log(label()); // 'Ada'
details.set('Programmer'); // label is not affected while showDetails() is false
showDetails.set(true);
console.log(label()); // 'Ada - Programmer'On the first read, showDetails is false, so the function reads only showDetails and name. Changing details does nothing to label. After showDetails becomes true, the next run also reads details, and from then on it is a dependency.
This keeps recalculation to a minimum. It also explains why a computed value can stop reacting to a signal that sits in a branch the function no longer takes.
Using computed in a component
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-cart',
template: `
<button (click)="add()">Add</button>
<p>{{ quantity() }} x {{ price() }} = {{ total() }}</p>
`,
})
export class CartComponent {
price = signal(10);
quantity = signal(1);
total = computed(() => this.price() * this.quantity());
add() {
this.quantity.update((q) => q + 1);
}
}The component only writes to quantity. The template shows total() and stays correct without any extra code.
Common mistakes
- Writing a signal inside computed. Angular raises an error for this, because a computed function must not change state.
- Forgetting the parentheses.
totalis the signal object.total()is its value. Usingprice * quantitywithout calls givesNaNor a type error. - Mutating an object or array in place. A signal compares values with
Object.is. If you callpush()on an array held in a signal, the reference does not change, and the computed value does not update. Create a new array withupdate()instead. - Side effects in the function. Logging or network calls inside
computed()run at unpredictable times. Use an effect for those, covered in a later chapter.
Exercise
A component has a = signal(1), b = signal(2) and sum = computed(() => { console.log('run'); return this.a() + this.b(); }). Nothing reads sum yet. You call a.set(5), then read sum() twice. How many times is "run" logged, and why?
Show answer
Once. The function does not run when sum is created or when a changes, because computed signals are lazy. The first read after the change runs it and stores the result. The second read returns the stored value, since no dependency has changed since.
Exercise
In the label example, showDetails is false and label() has been read once. You call details.set('Programmer') and read label() again. Does the function run again? Explain.
Show answer
No. During the last run the function never read details, so details is not a dependency. Only showDetails and name are tracked, and neither has changed, so the cached value is returned.