Sub topic 5
Derived values with withComputed
This chapter assumes you know Angular signals (signal, computed), the signalStore and withState setup from the earlier chapters, and basic TypeScript generics. You will learn how withComputed adds read-only derived values to a store, how those values behave at runtime, and which mistakes to avoid.
Why derive instead of store
State should hold the smallest set of facts that cannot be calculated from anything else. In a todo list, those facts are the todos array and the selected filter. The number of open todos and the list currently on screen can both be calculated from those two facts.
If you stored openCount as state, every method that changes todos would also have to update openCount. Forgetting one place leaves the store inconsistent. A derived value cannot go stale, because it is recalculated from the source facts.
withComputed is the store feature for this. It adds named computed signals to the store. Components read them like any other signal, and nothing outside the store can write to them.
The shape of withComputed
withComputed takes a factory function. The factory receives the store members defined so far, and it returns an object whose values are signals, usually created with computed.
import { computed } from '@angular/core';
import { signalStore, withComputed, withState } from '@ngrx/signals';
type Filter = 'all' | 'open' | 'done';
type Todo = { id: number; title: string; done: boolean };
type TodosState = { todos: Todo[]; filter: Filter };
const initialState: TodosState = { todos: [], filter: 'all' };
export const TodosStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
withComputed(({ todos, filter }) => {
const openCount = computed(() => todos().filter((t) => !t.done).length);
const visibleTodos = computed(() => {
switch (filter()) {
case 'open':
return todos().filter((t) => !t.done);
case 'done':
return todos().filter((t) => t.done);
default:
return todos();
}
});
return { openCount, visibleTodos };
}),
);Three details matter here.
- The parameter is the store, and each state property on it is a signal. Destructuring
{ todos, filter }gives you those signals. You call them (todos()) insidecomputed, which is what registers the dependency. - The factory body runs once, when the store is created. The
computedcalls inside it create the signals once. Only the inner arrow functions run again later. - The returned object is merged into the store. After this,
store.openCount()andstore.visibleTodos()exist, and so dostore.todos()andstore.filter().
How the dependencies flow
Each computed signal tracks the signals it read during its last calculation. When one of them changes, the computed signal is marked stale. It recalculates the next time something reads it.
This gives you two properties worth relying on.
- Lazy. A computed signal does no work until it is read. If no template reads
visibleTodos, its filter code never runs. - Memoized. The result is cached. Reading
store.openCount()ten times without a state change runs the calculation once.
Changing filter marks visibleTodos stale but leaves openCount untouched, because openCount never read filter. This is also why a switch like the one above is safe. Only the branch that runs reads signals, and the dependency set is rebuilt on each recalculation.
Using the values in a component
Components treat computed values the same as state. Call them in the template.
import { Component, inject } from '@angular/core';
import { TodosStore } from './todos.store';
@Component({
selector: 'app-todos',
template: `
<p>{{ store.openCount() }} open</p>
@for (todo of store.visibleTodos(); track todo.id) {
<label>
<input type="checkbox" [checked]="todo.done" (change)="store.toggle(todo.id)" />
{{ todo.title }}
</label>
}
`,
})
export class TodosComponent {
readonly store = inject(TodosStore);
}This component assumes the store also has the toggle method from the withMethods chapter. The template reads signals, so Angular re-renders only when openCount or visibleTodos produces a new value.
Building on other computed values
A computed signal can read another computed signal. In a store, order decides what is visible. Each with* feature sees only the members defined above it, so a second withComputed can use the results of the first.
import { computed } from '@angular/core';
import { signalStore, withComputed, withState } from '@ngrx/signals';
type Todo = { id: number; title: string; done: boolean };
export const ProgressStore = signalStore(
withState<{ todos: Todo[] }>({ todos: [] }),
withComputed(({ todos }) => ({
total: computed(() => todos().length),
doneCount: computed(() => todos().filter((t) => t.done).length),
})),
withComputed(({ total, doneCount }) => ({
percentDone: computed(() => (total() === 0 ? 0 : Math.round((doneCount() / total()) * 100))),
})),
);The second withComputed destructures total and doneCount, which only exist because the first one ran before it. If you swap the two calls, total is undefined at runtime and TypeScript reports an error at compile time. The same rule applies to methods: withMethods comes after withComputed, so a computed signal cannot call a store method.
Splitting into several small computed signals is usually better than one large one. Each piece is cached on its own, and each has a name you can test.
Injecting services
The factory runs in an injection context, the same as withMethods. You can inject services with inject() through a default parameter.
import { computed, inject, LOCALE_ID } from '@angular/core';
import { signalStore, withComputed, withState } from '@ngrx/signals';
export const PriceStore = signalStore(
withState({ amount: 0 }),
withComputed(({ amount }, locale = inject(LOCALE_ID)) => ({
formattedAmount: computed(() =>
amount().toLocaleString(locale, { style: 'currency', currency: 'EUR' }),
),
})),
);The second argument of the factory is never passed by the library. It is only a place to call inject() in a way that stays inside the injection context.
Equality and when consumers re-run
A computed signal notifies its readers only when its new result is different from the old one. By default, "different" means Object.is, which compares references for objects and arrays.
This has a consequence for derived collections. visibleTodos in the 'open' case builds a new array on every recalculation. It recalculates only when todos or filter changes, so the new reference is correct and the template updates. The cost appears when a computed signal builds a new object that is structurally the same as before, and a downstream computed signal runs again for nothing. For that case, computed accepts an equal option.
import { computed } from '@angular/core';
const sameIds = (a: number[], b: number[]) =>
a.length === b.length && a.every((id, i) => id === b[i]);
// Inside a withComputed factory:
// const openIds = computed(() => todos().filter((t) => !t.done).map((t) => t.id), { equal: sameIds });Reach for equal only after you have seen unnecessary recalculation. For most stores, the default is correct and simpler.
Common mistakes
- Mutating state inside a computed. A computed function must be pure. Do not call
patchState, make HTTP calls, or write to other signals from it. If you need a side effect when a value changes, use aneffector anrxMethodinstead. - Reading a signal without calling it.
todos.filter(...)fails becausetodosis a signal object, not an array. Writetodos().filter(...). - Reading outside tracking. A value you read in the factory body but outside a
computedis read once and never updated. Always read signals inside thecomputedcallback. - Storing derived data in state. If a method has to remember to update it, it belongs in
withComputed. - Doing heavy work for tiny gains. Memoization avoids repeated calculation, but a very expensive computation on a large list still runs on every change to its inputs. Keep computed functions cheap, or reduce what they depend on.
Quick comparison
| Question | State from `withState` | Computed from `withComputed` |
|---|---|---|
| Can a component write it? | Only through `patchState` in the store | No, it is read-only |
| Where does its value come from? | Set directly | Calculated from other signals |
| When does it run? | Not applicable | On first read, then after a dependency changes |
| What does `patchState` accept? | Its keys | Not its keys |
Checking your understanding
Exercise
Extend ProgressStore so that it also exposes remaining (the number of todos that are not done) without adding any new state, and explain why remaining should be a computed signal rather than a state property.
Show answer
Add remaining: computed(() => total() - doneCount()) to the second withComputed call, next to percentDone, because total and doneCount are already available there. It should be computed because it can always be calculated from todos. A state property would have to be updated by every method that changes todos, and any method that forgot would leave remaining out of date.
Exercise
A store has withComputed before withState, and the computed factory reads todos(). What happens, and how do you fix it?
Show answer
The todos member does not exist yet when the factory runs, so TypeScript reports an error, and at runtime reading it fails. Move withState above withComputed so the state signals are part of the store before the factory receives it.