Sub topic 2
Derived Values with `withComputed`
Assume you know Angular components, dependency injection, signals, TypeScript object types, and basic RxJS operators such as pipe and switchMap. This chapter shows how a SignalStore exposes derived data, state-changing methods, nested signals, and asynchronous loading.
Deriving values with `withComputed`
A computed value is a signal calculated from other signals. It updates automatically when its dependencies change. Keep values such as counts and filtered lists derived instead of storing duplicate state.
import { computed } from '@angular/core';
import {
patchState,
signalStore,
withComputed,
withMethods,
withState,
} from '@ngrx/signals';
type Todo = { id: number; title: string; done: boolean };
type Filter = 'all' | 'open' | 'done';
export const TodosStore = signalStore(
withState<{ todos: Todo[]; filter: Filter }>({
todos: [],
filter: 'all',
}),
withComputed(({ todos, filter }) => ({
openCount: computed(() => todos().filter((todo) => !todo.done).length),
visibleTodos: computed(() => {
const current = todos();
if (filter() === 'open') return current.filter((todo) => !todo.done);
if (filter() === 'done') return current.filter((todo) => todo.done);
return current;
}),
})),
withMethods((store) => ({
add(title: string): void {
patchState(store, {
todos: [
...store.todos(),
{ id: Date.now(), title, done: false },
],
});
},
setFilter(filter: Filter): void {
patchState(store, { filter });
},
})),
);Exposing operations with `withMethods`
Methods are the store’s public operations. Components call methods rather than changing signals directly. Use patchState for updates, and create new arrays or objects instead of mutating existing values.
Reading nested state with deep signals
When withState receives nested data, SignalStore exposes nested paths as signals. For example, a state field named profile can provide store.profile.name() and store.profile.settings.theme(). These paths are created as needed, so callers can read only the part they require.
withState({
profile: {
name: 'Mina',
settings: { theme: 'dark' as 'light' | 'dark' },
},
});
// In a component:
const name = store.profile.name();
const theme = store.profile.settings.theme();Loading data with `rxMethod`
rxMethod connects a store method to an RxJS pipeline. It can accept a value, signal, or observable. switchMap cancels an older request when a newer query arrives, while tapResponse handles success and failure.
loadByQuery: rxMethod<string>(
pipe(
tap(() => patchState(store, { loading: true, error: null })),
switchMap((query) =>
http.get<User[]>('/api/users', { params: { q: query } }).pipe(
tapResponse({
next: (users) => patchState(store, { users, loading: false }),
error: () => patchState(store, {
loading: false,
error: 'Could not load users',
}),
}),
),
),
),
),Exercise
Why should a filtered todo list usually be a computed signal instead of stored separately?
Show answer
It is derived from the todos and filter, so computing it avoids duplicate state that could become inconsistent.