Sub topic 11
Root-level versus component-level stores
This chapter assumes you can build a store with signalStore, withState, withComputed and withMethods. It also assumes you know how Angular's injector hierarchy resolves a dependency. The chapter shows how to choose where a store lives and what that choice changes.
A store is an injectable service
signalStore returns a class that Angular can inject. It has no special lifetime of its own. How long the state lives, and how many copies exist, depends on where you register the class with the dependency injection system.
There are three places to register it:
- The root injector, using
{ providedIn: 'root' }. - A component's
providersarray. - A route's
providersarray.
The choice decides three things:
- Instances: how many copies of the state exist.
- Lifetime: when the state is created and when it is destroyed.
- Visibility: which parts of the application can read it.
Root-level stores
Pass a configuration object as the first argument of signalStore:
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
type SessionState = { userName: string | null };
export const SessionStore = signalStore(
{ providedIn: 'root' },
withState<SessionState>({ userName: null }),
withMethods((store) => ({
signIn(userName: string): void {
patchState(store, { userName });
},
signOut(): void {
patchState(store, { userName: null });
},
})),
);Any component, service or guard can call inject(SessionStore) and receive the same instance. Angular creates the store the first time something injects it. It lives until the application is destroyed.
Use a root store for state that is global by nature:
- The signed-in user.
- Application settings and the theme.
- A shopping cart that the header, product pages and checkout all read.
- Data cached across several screens.
Two consequences matter in practice.
- State survives navigation. If a user leaves a page and returns, the store still holds the previous values. This is useful for a cache and a problem for a form draft.
- State is shared. Two components that inject the store write to the same signals. A change made in one is visible in the other immediately.
Component-level stores
Omit the configuration object, then list the store in the component's providers:
import { Component, inject } from '@angular/core';
import { patchState, signalStore, withHooks, withMethods, withState } from '@ngrx/signals';
type EditorState = { draft: string; saving: boolean };
export const EditorStore = signalStore(
withState<EditorState>({ draft: '', saving: false }),
withMethods((store) => ({
setDraft(draft: string): void {
patchState(store, { draft });
},
})),
withHooks({
onInit(store) {
console.log('EditorStore created, draft:', store.draft());
},
onDestroy() {
console.log('EditorStore destroyed');
},
}),
);
@Component({
selector: 'app-editor',
providers: [EditorStore],
template: `
<textarea [value]="store.draft()" (input)="onInput($event)"></textarea>
`,
})
export class EditorComponent {
readonly store = inject(EditorStore);
onInput(event: Event): void {
this.store.setDraft((event.target as HTMLTextAreaElement).value);
}
}Angular creates a new EditorStore each time an EditorComponent is created. When that component is destroyed, Angular destroys the store with it. The onDestroy hook runs, and any rxMethod subscriptions tied to the store's injector are cleaned up. The previous chapters on rxMethod and withHooks relied on this behavior.
A component-level store fits state that belongs to one screen or one widget:
- A form draft.
- The page, sort order and filter of one table.
- The open or closed state of a wizard.
If the user opens the screen again, they get fresh initial state.
The store is visible to the component's subtree
A provider on a component is available to that component, its template children and its content children. A child component can call inject(EditorStore) and will receive the parent's instance. This lets you split a large screen into small components that share one store without passing inputs through every level.
Siblings and ancestors cannot see it. A component outside the subtree that injects EditorStore fails with NullInjectorError, because the store is not registered on any injector it can reach.
The block above is empty by mistake and must not be used. The correct diagram follows.
Comparing the two
| Question | Root-level | Component-level |
|---|---|---|
| Registration | `signalStore({ providedIn: 'root' }, ...)` | `providers: [Store]` on a component |
| Instances | One for the application | One per component instance |
| Created | On first injection | When the component is created |
| Destroyed | When the application is destroyed | When the component is destroyed |
| State after leaving the page | Kept | Lost |
| Typical use | Session, settings, cache, cart | Form drafts, table state, wizard steps |
| Injecting where it is not provided | Always works | `NullInjectorError` outside the subtree |
Route-level stores
You can also register a store in a route's providers. Angular then creates an environment injector for that route, and every component rendered under the route can inject the store.
import { Routes } from '@angular/router';
import { OrdersStore } from './orders.store';
export const routes: Routes = [
{
path: 'orders',
providers: [OrdersStore],
loadComponent: () => import('./orders-page.component').then((m) => m.OrdersPageComponent),
children: [
{
path: ':id',
loadComponent: () => import('./order-detail.component').then((m) => m.OrderDetailComponent),
},
],
},
];The list page and the detail page now share one OrdersStore, which is useful when a master-detail flow needs the same loaded data.
Route injectors behave differently from component injectors. Angular creates the route's injector the first time the route is activated and keeps it. Navigating away does not destroy it, so the store keeps its state when the user comes back, and onDestroy does not run on navigation. Do not use a route-level store when you need a clean reset on every visit. A component-level store, or an explicit reset method called from onInit, gives you that.
Choosing: a decision procedure
- Does more than one unrelated part of the application need this state? Use a root store.
- Should the state outlive the screen, as with a cache or a signed-in user? Use a root store.
- Does one screen or widget own the state, and should it start fresh each time? Use a component-level store.
- Do several routes in one feature share data, with no need for it elsewhere? Use a route-level store.
If you are unsure, start with the narrowest scope that works. Widening a component-level store to root later means adding { providedIn: 'root' } and removing the providers entry. Narrowing a root store is harder, because other code may already depend on the global instance.
Common errors
NullInjectorError for a store without `providedIn`
A store declared without { providedIn: 'root' } is not registered anywhere. Injecting it before you list it in providers produces an error like NullInjectorError: No provider for EditorStore!. The fix is to add the store to a providers array on a component, route or application config that sits above every consumer.
Shadowing a root store by accident
Suppose a store is providedIn: 'root' and a component also lists it in providers. That component and its subtree get a separate instance, and the rest of the application keeps the root one. The two instances do not synchronize. This is legal, but it is usually a mistake. Pick one registration for each store. The sketch below shows the trap.
import { Component, inject } from '@angular/core';
import { SessionStore } from './session.store';
@Component({
selector: 'app-profile',
providers: [SessionStore], // creates a second SessionStore, separate from the root one
template: `<p>{{ session.userName() }}</p>`,
})
export class ProfileComponent {
readonly session = inject(SessionStore); // null here even when the user signed in elsewhere
}ProfileComponent shows null because its private copy starts with the initial state. Removing the providers line makes it read the root store.
Expecting state to reset on a root store
A root store keeps its values after the user leaves a page. If a form reads from a root store, the user sees old input when they return. Either move the form state into a component-level store or add a reset method that calls patchState with the initial state.
Injecting a component-level store from a parent
A parent component cannot inject a store that its child provides. The injector lookup walks up the tree, never down. If both need the store, provide it on the parent, or on a common ancestor.
Starting requests that never end
An rxMethod created in a root store runs until the application is destroyed, because the root injector is never destroyed during normal use. If its source signal changes often, make sure switchMap cancels the previous request. A component-level store avoids a long-lived subscription, because Angular cleans up its rxMethod calls when the component goes away.
Testing both kinds
A root store needs no setup in a test. TestBed.inject(SessionStore) returns the application-wide instance for that test, and TestBed creates a new root injector for each test, so state does not leak between tests.
A component-level store has no root registration, so TestBed.inject fails unless you register it:
import { TestBed } from '@angular/core/testing';
import { EditorStore } from './editor.store';
describe('EditorStore', () => {
beforeEach(() => {
TestBed.configureTestingModule({ providers: [EditorStore] });
});
it('starts with an empty draft and updates it', () => {
const store = TestBed.inject(EditorStore);
expect(store.draft()).toBe('');
store.setDraft('Hello');
expect(store.draft()).toBe('Hello');
});
});This tests the store without rendering the component. To test the component itself, declare the store in its providers as usual. You can also override that provider with a fake in TestBed.overrideComponent.
Summary
- A signal store is an injectable class. Its scope is set by where you register it.
{ providedIn: 'root' }gives one instance that lives as long as the application.- A component's
providersgives one instance per component, destroyed with it, visible to its subtree. - A route's
providersgives one instance shared by the route's components, kept after navigation. - Registering a root store a second time in a component creates an unrelated copy.
Exercise
A product page has a filter panel that holds search text and a sortOrder. Users expect the panel to start empty each time they open the page. A separate CartStore holds the items the user plans to buy, and the header badge must show the count on every page. Decide the scope of each store and name the Angular mechanism that gives each scope.
Show answer
Make CartStore a root store with signalStore({ providedIn: 'root' }, ...), because several unrelated parts of the app (header and product pages) share it and it must outlive any one page. Make the filter store a component-level store by leaving out providedIn and listing it in the page component's providers. Angular then creates a fresh instance each time the page opens and destroys it when the page closes, so the filter starts empty.
Exercise
A developer lists SessionStore (declared with providedIn: 'root') in the providers of ProfileComponent. After the user signs in through the header, ProfileComponent still shows no user name. Why, and what is the fix?
Show answer
The providers entry makes Angular create a second SessionStore for ProfileComponent and its subtree. That copy has its own initial state and is not updated by the header's sign-in, which writes to the root instance. Remove SessionStore from the component's providers so inject(SessionStore) resolves to the root instance.
Exercise
Your test calls TestBed.inject(EditorStore) and fails with NullInjectorError. EditorStore has no providedIn setting. What do you add to the test?
Show answer
Register the store in the test module: TestBed.configureTestingModule({ providers: [EditorStore] }), before calling TestBed.inject(EditorStore). A store without providedIn: 'root' is not registered anywhere by default.