Sub topic 11
Root-level versus component-level stores
This chapter assumes you can build a store with signalStore, withState and withMethods, and that you know how Angular's injector hierarchy resolves a provider. A signal store is an injectable service. Where you register it decides how many instances exist and how long their state lives.
Two ways to provide a store
You choose the scope when you define the store.
- Root-level: pass
{ providedIn: 'root' }as the first argument. Angular creates one instance for the whole application, and every consumer shares it. - Component-level: omit
providedInand list the store in aprovidersarray. Angular creates a new instance for each place that provides it.
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
// One instance for the whole app
export const SessionStore = signalStore(
{ providedIn: 'root' },
withState({ userName: null as string | null }),
withMethods((store) => ({
signIn(userName: string): void {
patchState(store, { userName });
},
})),
);
// No providedIn: it must be provided where it is used
export const CounterStore = signalStore(
withState({ count: 0 }),
withMethods((store) => ({
increment(): void {
patchState(store, (state) => ({ count: state.count + 1 }));
},
})),
);Providing a store on a component
Add the store to the component's providers. The component and all its children can then inject it.
import { Component, inject } from '@angular/core';
import { CounterStore } from './counter.store';
@Component({
selector: 'app-counter',
providers: [CounterStore],
template: `
<button (click)="store.increment()">Clicked {{ store.count() }} times</button>
`,
})
export class CounterComponent {
readonly store = inject(CounterStore);
}If you render <app-counter /> twice, each copy gets its own store and its own count. When Angular destroys a copy, it destroys that copy's store, and any onDestroy hook you defined with withHooks runs.
You can use the same providers array on a route to scope a store to a feature area.
import { Routes } from '@angular/router';
import { CounterStore } from './counter.store';
export const routes: Routes = [
{
path: 'counter',
loadComponent: () => import('./counter.component').then((m) => m.CounterComponent),
providers: [CounterStore],
},
];Every component under that route shares one instance. The instance lives until the route's injector is destroyed.
How instances are resolved
Both counters can inject SessionStore and see the same user name. Each keeps its own CounterStore count.
Choosing a scope
| Question | Root-level | Component-level |
|---|---|---|
| Who shares the state? | The whole app | One component and its children |
| When is state reset? | Never, unless you reset it | When the component is destroyed |
| Typical use | Session, settings, cart | A form, a table, a dialog |
| Testing setup | `TestBed.inject` works directly | Needs `providers` in `TestBed` |
Start with component-level for state that belongs to one screen. Promote a store to root only when unrelated parts of the app need the same data.
Common errors
NullInjectorError: No provider for CounterStore. The store has noprovidedInand nothing in the injector chain provides it. Add it toproviders.- State that "leaks" between screens. A root store keeps its values after you navigate away. If a screen should start fresh, scope the store to that screen.
- Two components that should share state show different data. Each component lists the store in its own
providers, so each gets its own instance. Provide it once on a common parent or a route.
Testing a component-level store
TestBed.inject only finds stores that are provided. For a store without providedIn, register it first.
import { TestBed } from '@angular/core/testing';
import { CounterStore } from './counter.store';
describe('CounterStore', () => {
it('increments the count', () => {
TestBed.configureTestingModule({ providers: [CounterStore] });
const store = TestBed.inject(CounterStore);
store.increment();
expect(store.count()).toBe(1);
});
});Exercise
A product list page and its filter sidebar must share one store, but the store's state must reset each time the user leaves and re-enters the page. Where should you provide the store, and why?
Show answer
Provide it on the page component (or on the page's route), without providedIn: 'root'. The sidebar is a child, so it injects the same instance. Angular destroys the instance when the page is destroyed, so the next visit starts from the initial state.