Sub topic 1
Why SignalStore and Where It Fits
Prerequisites
Assume you know Angular components, dependency injection, signals, TypeScript object types, and basic RxJS. A signal is a value that notifies consumers when it changes. NgRx SignalStore uses signals to expose application state.
Why SignalStore and Where It Fits
NgRx SignalStore is a lightweight way to organize state in an Angular service. A store combines state, derived values, and methods that change the state.
The traditional NgRx Store is a good choice for large applications that need actions, reducers, effects, and a centralized event log. ComponentStore provides localized state with an RxJS-oriented API. SignalStore is also localized and composable, but its public state is read as signals and its updates are usually direct method calls.
| Option | Typical strength | State is commonly read as |
|---|---|---|
| NgRx Store | Centralized, event-driven application state | Selectors or signals |
| ComponentStore | Local state with RxJS workflows | Observables |
| SignalStore | Local, signal-first feature state | Signals |
Use SignalStore when a feature has shared state or nontrivial update logic, but does not need the ceremony of a global action and reducer system.
flowchart TD
C[Angular component] --> S[SignalStore]
S --> ST[State signals]
S --> D[Computed signals]
C --> M[Store methods]
M --> P[patchState]
P --> STCreating Your First Store with `signalStore`
A store is assembled from features. withState adds writable state, withComputed adds derived signals, and withMethods adds operations.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type CounterState = { count: number };
export const CounterStore = signalStore(
withState<CounterState>({ count: 0 }),
withMethods((store) => ({
increment(): void {
patchState(store, (state) => ({ count: state.count + 1 }));
},
})),
);Inject CounterStore into a component. Read store.count() in the template and call store.increment() from an event handler.
Defining and Updating State
withState defines the initial shape and types of state. patchState applies a partial update or a function based on the current state. The functional form is useful when the next value depends on the previous value.
Update arrays and objects immutably: create a new array or object instead of changing the existing value.
Exercise
Why should patchState update an array with [...state.items, item] instead of state.items.push(item)?
Show answer
The spread expression creates a new array, so Angular signals can detect the changed reference and notify consumers.