Sub topic 2
Creating your first store with signalStore
This chapter assumes you know Angular components, dependency injection and signals (signal, computed). You will build a minimal store, learn what signalStore returns, and learn the rules that decide what the finished store exposes. Later chapters cover each feature (withState, withComputed, withMethods) in more depth. Here the goal is to understand how the pieces fit together.
What signalStore returns
signalStore is a function from @ngrx/signals. You call it with an optional configuration object followed by any number of store features. It returns a class, not an instance. Angular creates the instance when the class is injected, as it does for any service.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
export const CounterStore = signalStore(
{ providedIn: 'root' },
withState({ count: 0 }),
withMethods((store) => ({
increment(): void {
patchState(store, (state) => ({ count: state.count + 1 }));
},
reset(): void {
patchState(store, { count: 0 });
},
})),
);This definition has three parts:
{ providedIn: 'root' }is the configuration. It makes the class a root-level singleton, the same as@Injectable({ providedIn: 'root' })on a service.withState({ count: 0 })is a feature that adds state.withMethods(...)is a feature that adds operations. It receives the store built so far, so it can readcountand callpatchState.
A component injects the store and uses it:
import { Component, inject } from '@angular/core';
import { CounterStore } from './counter.store';
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ store.count() }}</p>
<button (click)="store.increment()">Add</button>
<button (click)="store.reset()">Reset</button>
`,
})
export class CounterComponent {
readonly store = inject(CounterStore);
}store.count is a signal, so the template calls it. Angular's change detection tracks that read and updates the view when count changes.
How features compose
A store is built by applying features from top to bottom. Each feature receives the store as built so far and returns a new store with extra members added. The final result is what the injected instance exposes.
The diagram shows the features as parallel inputs, but they run in order. Each feature can use only what the features above it added.
Order matters
Features only see members from earlier features. A withComputed placed above withState cannot read state, and TypeScript reports an error because the property does not exist yet.
import { computed } from '@angular/core';
import { signalStore, withComputed, withState } from '@ngrx/signals';
export const PriceStore = signalStore(
withState({ price: 10, quantity: 3 }),
withComputed(({ price, quantity }) => ({
total: computed(() => price() * quantity()),
})),
);If you swap the two features, the destructuring of price and quantity fails to compile. This is a useful property. The compiler checks your dependencies between features, so you don't find the mistake at runtime.
The same rule applies to names. If a later feature adds a member with the same name as an earlier one, the later one replaces it. Recent NgRx versions warn about this in development mode. Pick distinct names for state, computed signals and methods.
What the store exposes
The injected instance has these members:
| Source | Member on the store | Type |
|---|---|---|
| `withState({ count: 0 })` | `store.count` | `Signal<number>` |
| `withComputed(...)` | the keys you return | `Signal<T>` |
| `withMethods(...)` | the methods you return | plain functions |
Each top-level property of the state object becomes its own signal. The store does not expose one big state signal. Reading store.count() creates a dependency on count only, so a component that reads one property is not affected by changes to the others.
To get a plain snapshot of all state, for logging or debugging, use getState:
import { getState } from '@ngrx/signals';
// Inside a method or an effect, where `store` is the store instance:
console.log(getState(store)); // { count: 0 }State is protected from outside writes
In current NgRx versions, state is protected by default. Only code inside the store can call patchState on it. A component that tries patchState(this.store, { count: 5 }) gets a compile error. This keeps every state change in one place: the store's methods.
Because writes go through methods, the public API of a store is its methods plus its read-only signals. That is the contract components rely on.
Configuration options
The first argument is optional. These are the two options you will use:
| Option | Effect |
|---|---|
| `providedIn: 'root'` | One instance for the whole app, created on first injection. |
| `protectedState: false` | Allows `patchState` calls from outside the store. |
Without providedIn, the store is not registered anywhere. You must list it in a providers array. The next sections show both approaches. Chapter 11 covers the trade-offs between them in detail.
Root-level store
With providedIn: 'root', any component or service can call inject(CounterStore) and gets the same instance. State persists as long as the app runs.
Provided where you need it
import { Component, inject } from '@angular/core';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
const FormStore = signalStore(
withState({ draft: '' }),
withMethods((store) => ({
setDraft(draft: string): void {
patchState(store, { draft });
},
})),
);
@Component({
selector: 'app-note-editor',
providers: [FormStore],
template: `
<input [value]="store.draft()" (input)="store.setDraft($any($event.target).value)" />
<p>{{ store.draft().length }} characters</p>
`,
})
export class NoteEditorComponent {
readonly store = inject(FormStore);
}Here the store has no providedIn. The component lists it in providers, so each component instance gets its own store, and Angular destroys the store when the component is destroyed. Use this for state that belongs to one screen or one widget.
Initial state
withState accepts either an object or a factory function. The factory form is useful when the initial value must be computed fresh for each store instance, or depends on injected services.
import { signalStore, withState } from '@ngrx/signals';
type SettingsState = { theme: 'light' | 'dark'; createdAt: number };
export const SettingsStore = signalStore(
{ providedIn: 'root' },
withState<SettingsState>(() => ({
theme: 'light',
createdAt: Date.now(),
})),
);Passing the generic type, as in withState<SettingsState>, gives you precise types. Without it, TypeScript infers theme as string from a literal, which is wider than you want.
Some constraints on state shape:
- State must be a plain object. Primitives, arrays and class instances cannot be the root state.
- Top-level keys become signals, so choose keys that read well as
store.key(). - Keys that start with
__or clash with other members can lead to confusing behavior. Avoid them.
Common errors
- Reading a signal without calling it.
{{ store.count }}prints the function, not the value. Write{{ store.count() }}. - Putting a feature above the one it needs.
withMethodsthat readsstore.countmust come afterwithState. The compiler reports that the property does not exist. - Forgetting to provide the store. If you omit
providedInand don't list the class inproviders, Angular throws aNullInjectorErrorwhen you inject it. - Calling
patchStatefrom a component. With protected state, this fails to compile. Move the write into a store method. - Mutating state.
store.todos().push(item)changes data that signals consider unchanged, so views do not update. Always produce new objects withpatchState, which is the subject of the next chapter. - Expecting an instance from
signalStore. The returned value is a class. You can't callCounterStore.count()directly. You must inject it.
Where this fits
A store from signalStore is a service with a structured shape. It holds state, derives values and exposes methods, all as one injectable unit. Compare that with a hand-written service that has several signal() fields. You get the same reactivity, but you also get a consistent layout, protected writes, type-checked feature order, and the ability to add shared features such as entities or a request status with one line.
Exercise
You write signalStore(withMethods((store) => ({ double(): void { patchState(store, { count: store.count() * 2 }); } })), withState({ count: 1 })). The compiler reports an error on store.count. What is wrong, and how do you fix it? Also, what extra step do you need if you leave out providedIn: 'root' and want each component to have its own copy of the store?
Show answer
withMethods comes before withState, so store.count does not exist yet when withMethods runs. Features see only what earlier features added. Move withState({ count: 1 }) above withMethods. If the store has no providedIn: 'root', list the store class in the component's providers array. Then inject it with inject(). Each component instance then gets its own store, which Angular destroys together with the component.
Exercise
A component template contains {{ store.count }} and shows function source text instead of a number. Why does this happen, and why can't the component fix its count by calling patchState(this.store, { count: 0 }) when the store uses default settings?
Show answer
Each state property is a signal, which is a function, so you must call it as store.count() to read the value. Writing store.count prints the function itself. State is protected by default, so patchState on the store only compiles inside the store's own features. The component should call a store method such as reset() that performs the update.