Sub topic 5
Derived values with withComputed
This chapter assumes you know Angular signals (signal, computed), have read the earlier chapters on withState and patchState, and are comfortable with TypeScript object types. It covers how to add derived values to a signal store with withComputed, and the mistakes people make with it.
What withComputed does
Some values are not stored. They are calculated from state: the number of open todos, the todos that match a filter, a total price. If you store them as state, you must keep them in sync by hand, and sooner or later they drift.
withComputed adds read-only computed signals to a store. Angular recalculates each one only when a signal it read has changed, and it caches the result until then.
A feature function passed to signalStore receives the store as built so far. Anything added by earlier features is available, so withComputed must come after withState.
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 };
}),
);How the factory works
The callback gets an object that contains the state signals (todos, filter) and anything else defined earlier. You destructure what you need, build computed signals, and return an object. Each key in that object becomes a property on the store.
The diagram below shows the data flow.
The store now exposes store.openCount() and store.visibleTodos(). A component reads them like any other signal, and the template updates when their inputs change.
Computed values can build on each other
Later withComputed calls see the signals returned by earlier ones. You can split derived values into steps:
import { computed } from '@angular/core';
import { signalStore, withComputed, withState } from '@ngrx/signals';
type CartState = { prices: number[]; taxRate: number };
export const CartStore = signalStore(
withState<CartState>({ prices: [], taxRate: 0.2 }),
withComputed(({ prices }) => ({
subtotal: computed(() => prices().reduce((sum, p) => sum + p, 0)),
})),
withComputed(({ subtotal, taxRate }) => ({
total: computed(() => subtotal() * (1 + taxRate())),
})),
);The second block reads subtotal, which the first block defined. If you swapped the two blocks, TypeScript would report that subtotal does not exist.
Common errors
- Storing derived data in state. A
visibleTodosarray inwithStatehas to be updated in every method that touchestodosorfilter. Compute it instead. - Mutating inside a computed. A computed signal must be a pure function of other signals. Do not call
patchStateor fetch data inside it. Put that work inwithMethodsorrxMethod. - Returning a new object every time for no reason. Computeds compare results by reference. A computed that builds a fresh array each run notifies its readers on every recalculation. This is normal for filtering, but avoid doing extra work in the template that repeats it.
- Wrong feature order. A feature can only use what was defined above it. If TypeScript says a property does not exist, check the order.
- Forgetting the call. Computed signals are functions. Use
store.openCount()in templates and code, notstore.openCount.
Computed values and methods
Use a computed for a value that depends only on state and has no arguments. Use a method in withMethods for something that takes parameters or changes state. For example, openCount fits withComputed, while toggle(id) belongs in withMethods.
| Need | Use |
|---|---|
| A value derived from state, no arguments | `withComputed` |
| An action that changes state | `withMethods` with `patchState` |
| A lookup that needs an argument | A method, or a computed over a map |
Exercise
A store has withState({ items: [] as { price: number; qty: number }[] }). Write a withComputed block that exposes totalQty, the sum of all qty values. Why is this better than adding totalQty to the state?
Show answer
withComputed(({ items }) => ({ totalQty: computed(() => items().reduce((sum, i) => sum + i.qty, 0)) })). It is better because the value is always derived from items, so it cannot get out of sync, and no method has to remember to update it.