Sub topic 2
Deriving state with computed()
This chapter assumes you know basic TypeScript, Angular components with templates and dependency injection, and the idea that change detection decides when a view updates. It also assumes you have used signal(), set() and update(). Later chapters cover laziness, caching and dynamic dependencies in depth. Here you learn how to write a computed signal, how to use it, and which mistakes to avoid.
The problem computed() solves
Applications keep a small amount of source state and a lot of values that follow from it. A cart has line items, and the total, the item count and the "is empty" flag all follow from those items. If you store each of these in its own writable signal, you must update all of them every time the source changes. Forget one and the screen shows inconsistent data.
A computed signal removes that work. You describe how the value is calculated, and Angular keeps it consistent with its inputs.
Your first computed signal
computed() takes a function, called the computation, and returns a read-only signal. Angular records which signals the function reads. Those signals are the dependencies of the computed value.
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, exactly like a writable signal. The computation reads price() and quantity(), so both become dependencies of total. When quantity changes to 3, total is marked stale. The next call to total() runs the computation again and returns 30.
What type you get back
computed() returns a Signal<T>, not a WritableSignal<T>. The type T is inferred from the return value of the computation.
| Feature | `signal()` | `computed()` |
|---|---|---|
| Type | `WritableSignal<T>` | `Signal<T>` |
| Read with `x()` | Yes | Yes |
| `set()` and `update()` | Yes | No |
| Value comes from | You | Other signals |
| Initial value | Required | Calculated on first read |
Because there is no set() method, the compiler rejects this:
import { signal, computed } from '@angular/core';
const count = signal(1);
const doubled = computed(() => count() * 2);
// Compile error: Property 'set' does not exist on type 'Signal<number>'.
doubled.set(10);This is deliberate. A derived value has one source of truth, which is its computation. If you could overwrite it, it could disagree with the signals it is derived from. If you need a derived value that you can also overwrite, that is a different tool, linkedSignal(), covered in a later chapter.
Using computed() in a component
Declare computed signals as class fields next to the signals they depend on. Read them in the template with parentheses.
import { Component, signal, computed } from '@angular/core';
interface CartItem {
name: string;
price: number;
quantity: number;
}
@Component({
selector: 'app-cart',
template: `
<ul>
@for (item of items(); track item.name) {
<li>{{ item.name }} x {{ item.quantity }}</li>
}
</ul>
<p>Items: {{ itemCount() }}</p>
<p>Total: {{ total() }}</p>
@if (isEmpty()) {
<p>Your cart is empty.</p>
}
<button (click)="addBook()">Add a book</button>
`,
})
export class CartComponent {
items = signal<CartItem[]>([]);
itemCount = computed(() =>
this.items().reduce((sum, item) => sum + item.quantity, 0)
);
total = computed(() =>
this.items().reduce((sum, item) => sum + item.price * item.quantity, 0)
);
isEmpty = computed(() => this.items().length === 0);
addBook() {
this.items.update((list) => [
...list,
{ name: 'Book', price: 12, quantity: 1 },
]);
}
}Three computed signals read the same items signal. Only items is ever written. When addBook() runs, the template reads itemCount(), total() and isEmpty() and gets fresh values. The template itself is a reactive consumer: Angular tracks which signals it reads and refreshes the view when one of them changes.
Notice that addBook() creates a new array with the spread operator instead of calling push(). A signal notices a change only when its value is replaced with a different value. Mutating the array in place leaves the same reference, so the signal does not notify its dependents, and your computed signals show stale results. Treat signal values as immutable.
Computed signals can depend on computed signals
A computation may read any signal, including other computed signals. This lets you build small steps instead of one large expression.
import { signal, computed } from '@angular/core';
const subtotal = signal(100);
const taxRate = signal(0.2);
const shipping = signal(5);
const tax = computed(() => subtotal() * taxRate());
const grandTotal = computed(() => subtotal() + tax() + shipping());
console.log(grandTotal()); // 125
taxRate.set(0.1);
console.log(grandTotal()); // 115The dependencies form a graph: subtotal and taxRate feed tax, and subtotal, tax and shipping feed grandTotal.
Changing taxRate marks tax stale, and tax in turn marks grandTotal stale. Changing shipping marks only grandTotal stale. You never describe these update paths. They follow from what each computation reads.
The graph must not contain a cycle. If a reads b and b reads a, Angular throws an error when you read either one, because the value has no starting point.
Computed signals with inputs
Signal inputs are read-only signals, so they combine well with computed(). A common use is turning raw inputs into display values.
import { Component, input, computed } from '@angular/core';
@Component({
selector: 'app-user-badge',
template: `<span>{{ initials() }} ({{ displayName() }})</span>`,
})
export class UserBadgeComponent {
firstName = input.required<string>();
lastName = input.required<string>();
displayName = computed(() => `${this.firstName()} ${this.lastName()}`);
initials = computed(
() => this.firstName().charAt(0) + this.lastName().charAt(0)
);
}When the parent passes a new firstName, both computed values are marked stale and the template shows updated text. You do not need ngOnChanges for this, and you do not copy the input into a second field.
One ordering rule applies. Field initializers run during construction, but required inputs have no value until Angular sets them. Defining the computed signal in a field is safe, because the computation does not run until something reads it. Reading this.firstName() directly in the constructor body would throw, because the input is not set yet.
Rules for the computation function
Angular calls your computation whenever it needs a fresh value, and it decides when. Write the function so that this is safe.
- Keep it pure. The same signal values in should give the same result out. Do not log, make HTTP calls, touch the DOM or start timers inside a computation. Those belong in effects or event handlers, which later chapters cover.
- Do not write to signals. Calling
set()orupdate()on a signal inside a computation throws an error, because a read must never change state. If you feel the need to write, you probably want an effect, an event handler orlinkedSignal(). - Read every signal you depend on. Only signals called during the computation count as dependencies. A plain property such as
this.discountthat is not a signal does not trigger recalculation when it changes. - Return a value, do not mutate one. A computation that sorts
this.items()in place withsort()mutates the source array. Copy first:[...this.items()].sort(...). - Keep it cheap and synchronous. A computation cannot be
async. If you return a promise, you get a signal holding a promise, not the resolved value.
Here is rule 4 in code:
import { signal, computed } from '@angular/core';
const numbers = signal([3, 1, 2]);
// Wrong: sort() reorders the array held by the signal.
// const sortedBad = computed(() => numbers().sort());
// Right: copy, then sort.
const sorted = computed(() => [...numbers()].sort((a, b) => a - b));
console.log(sorted()); // [1, 2, 3]
console.log(numbers()); // [3, 1, 2]Errors inside a computation
If the computation throws, reading the signal throws the same error. Angular remembers the error, so repeated reads do not re-run the function until a dependency changes. Once a dependency changes, the next read tries again.
import { signal, computed } from '@angular/core';
const text = signal('{"a":1}');
const parsed = computed(() => JSON.parse(text()));
console.log(parsed()); // { a: 1 }
text.set('{oops');
try {
parsed();
} catch (e) {
console.log('invalid JSON');
}
text.set('{"a":2}');
console.log(parsed()); // { a: 2 }Because a template reads the signal, an uncaught error in a computation surfaces as a rendering error. For input you do not control, catch inside the computation and return a safe value such as null.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Reading a non-signal field in the computation | The value never refreshes when the field changes | Make the field a signal |
| Forgetting `()` in `computed(() => this.count * 2)` | The compiler flags arithmetic on a function, or you get `NaN` | Call the signal: `this.count()` |
| Mutating an array or object signal in place | Dependents never recalculate | Replace the value with a new array or object |
| Writing to a signal in the computation | Angular throws an error | Move the write to an event handler or use `linkedSignal()` |
| Copying a signal's value into a plain variable outside the computation | The copy goes stale | Read the signal inside the computation |
| Using `computed()` to run a side effect | The code runs at unpredictable times, or never | Use `effect()` |
When computed() is the right choice
Reach for computed() when a value can be fully calculated from other signals, and nothing needs to happen as a result other than the value existing. Totals, filtered lists, formatted labels, validity flags and view-model objects fit this description. If you find yourself writing an effect that only calls set() on another signal to keep it in sync, replace the pair with a computed signal. Chapter 6 compares computed signals, effects and event handlers in detail.
Exercise
A component has items = signal<string[]>([]). A developer adds a button handler that calls this.items().push('x') and a field count = computed(() => this.items().length). After clicking, the template still shows 0. Explain why, and show the corrected handler.
Show answer
push() mutates the existing array, so the signal's value keeps the same reference. The signal sees no change and does not mark count stale, so the template shows the old cached value. The handler must replace the value: this.items.update((list) => [...list, 'x']);. The new array has a different reference, so items notifies its dependents and count() recalculates to 1.
Exercise
Write a computed signal named canCheckout that is true only when the cart in items = signal<{ price: number; quantity: number }[]>([]) is not empty and acceptedTerms = signal(false) is true. Then say which type TypeScript gives it.
Show answer
canCheckout = computed(() => this.items().length > 0 && this.acceptedTerms()); The inferred type is Signal<boolean>. It is read-only, so calling canCheckout.set(true) is a compile error.