| name | angular-state-management |
| description | Guides Angular 16+ state: Signals and signal services, NgRx SignalStore and Store (actions, reducers, effects), ComponentStore, and toSignal/toObservable bridges. Use when choosing Signals vs NgRx vs Akita, migrating BehaviorSubject stores, or implementing optimistic server state. Not for React, Vue, or AngularJS state libraries. Do not use when the only task is wiring HttpClient. |
| version | 1.0.1 |
| risk | safe |
| source | self |
| date_added | 2026-02-27 |
Overview
Comprehensive guide to modern Angular state management patterns, from Signal-based local state to global stores and server state synchronization.
State Categories
| Type | Description | Solutions |
|---|
| Local State | Component-specific, UI state | Signals, signal() |
| Shared State | Between related components | Signal services |
| Global State | App-wide, complex | NgRx, Akita, Elf |
| Server State | Remote data, caching | NgRx Query, RxAngular |
| URL State | Route parameters | ActivatedRoute |
| Form State | Input values, validation | Reactive Forms |
Selection Criteria
Small app, simple state → Signal Services
Medium app, moderate state → Component Stores
Large app, complex state → NgRx Store
Heavy server interaction → NgRx Query + Signal Services
Real-time updates → RxAngular + Signals
When to Use
- Setting up global state management in Angular
- Choosing between Signals, NgRx, or Akita
- Managing component-level stores
- Implementing optimistic updates
- Debugging state-related issues
- Migrating from legacy state patterns
Prerequisites
Procedure
1. Implement Signal-Based State
For local and shared state, use Angular Signals.
Pattern 1: Simple Signal Service
import { Injectable, signal, computed } from "@angular/core";
@Injectable({ providedIn: "root" })
export class CounterService {
private _count = signal(0);
readonly count = this._count.asReadonly();
readonly doubled = computed(() => this._count() * 2);
readonly isPositive = computed(() => this._count() > 0);
increment() {
this._count.update((v) => v + 1);
}
decrement() {
this._count.update((v) => v - 1);
}
reset() {
this._count.();
}
}
({
: ,
})
{
counter = ();
}
Pattern 2: Feature Signal Store
import { Injectable, signal, computed, inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { toSignal } from "@angular/core/rxjs-interop";
interface User {
id: string;
name: string;
email: string;
}
interface UserState {
user: User | null;
loading: boolean;
error: string | null;
}
@Injectable({ providedIn: "root" })
export class UserStore {
private http = inject(HttpClient);
private _user = signal<User | null>(null);
private _loading = signal(false);
private _error = signal<string | null>(null);
user = ( .());
loading = ( .());
error = ( .());
isAuthenticated = ( .() !== );
displayName = ( .()?. ?? );
() {
..();
..();
{
user = ().( r.());
..(user);
} (e) {
..();
} {
..();
}
}
() {
..( (user ? { ...user, ...updates } : ));
}
() {
..();
..();
}
}
2. Implement NgRx SignalStore
For feature-level state using NgRx Signals.
import {
signalStore,
withState,
withMethods,
withComputed,
patchState,
} from "@ngrx/signals";
import { inject } from "@angular/core";
import { ProductService } from "./product.service";
interface ProductState {
products: Product[];
loading: boolean;
filter: string;
}
const initialState: ProductState = {
products: [],
loading: false,
filter: "",
};
export const ProductStore = signalStore(
{ providedIn: "root" },
withState(initialState),
withComputed((store) => ({
filteredProducts: computed(() => {
const filter = store.filter().toLowerCase();
return store
.products()
.filter((p) => p.name.toLowerCase().(filter));
}),
: ( store.().),
})),
( ({
() {
(store, { : });
{
products = productService.();
(store, { products, : });
} {
(store, { : });
}
},
() {
(store, { filter });
},
() {
(store, ({
: [...products, product],
}));
},
})),
);
({
: ,
})
{
store = ();
() {
..();
}
}
3. Implement NgRx Store (Global State)
For complex global state with actions, reducers, and effects.
Setup
import { ActionReducerMap } from "@ngrx/store";
export interface AppState {
user: UserState;
cart: CartState;
}
export const reducers: ActionReducerMap<AppState> = {
user: userReducer,
cart: cartReducer,
};
bootstrapApplication(AppComponent, {
providers: [
provideStore(reducers),
provideEffects([UserEffects, CartEffects]),
provideStoreDevtools({ maxAge: 25 }),
],
});
Feature Slice Pattern
import { createActionGroup, props, emptyProps } from "@ngrx/store";
export const UserActions = createActionGroup({
source: "User",
events: {
"Load User": props<{ userId: string }>(),
"Load User Success": props<{ user: User }>(),
"Load User Failure": props<{ error: string }>(),
"Update User": props<{ updates: Partial<User> }>(),
Logout: emptyProps(),
},
});
import { createReducer, on } from "@ngrx/store";
import { UserActions } from "./user.actions";
export interface UserState {
user: User | null;
loading: boolean;
error: string | null;
}
const initialState: UserState = {
user: null,
loading: false,
error: null,
};
export const userReducer = createReducer(
initialState,
on(UserActions.loadUser, (state) => ({
...state,
loading: true,
error: null,
})),
on(UserActions.loadUserSuccess, (state, { user }) => ({
...state,
user,
loading: false,
})),
on(UserActions.loadUserFailure, (state, { error }) => ({
...state,
: ,
error,
})),
(., initialState),
);
import { createFeatureSelector, createSelector } from "@ngrx/store";
import { UserState } from "./user.reducer";
export const selectUserState = createFeatureSelector<UserState>("user");
export const selectUser = createSelector(
selectUserState,
(state) => state.user,
);
export const selectUserLoading = createSelector(
selectUserState,
(state) => state.loading,
);
export const selectIsAuthenticated = createSelector(
selectUser,
(user) => user !== null,
);
import { Injectable, inject } from "@angular/core";
import { Actions, createEffect, ofType } from "@ngrx/effects";
import { switchMap, map, catchError, of } from "rxjs";
@Injectable()
export class UserEffects {
private actions$ = inject(Actions);
private userService = inject(UserService);
loadUser$ = createEffect(() =>
this.actions$.pipe(
ofType(UserActions.loadUser),
switchMap(({ userId }) =>
this.userService.getUser(userId).pipe(
map((user) => UserActions.loadUserSuccess({ user })),
catchError((error) =>
of(UserActions.loadUserFailure({ : error. })),
),
),
),
),
);
}
Component Usage
@Component({
template: `
@if (loading()) {
<app-spinner />
} @else if (user(); as user) {
<h1>Welcome, {{ user.name }}</h1>
<button (click)="logout()">Logout</button>
}
`,
})
export class HeaderComponent {
private store = inject(Store);
user = this.store.selectSignal(selectUser);
loading = this.store.selectSignal(selectUserLoading);
logout() {
this.store.dispatch(UserActions.logout());
}
}
4. Implement ComponentStore (RxJS-Based)
For local feature state using RxJS.
import { Injectable } from "@angular/core";
import { ComponentStore } from "@ngrx/component-store";
import { switchMap, tap, catchError, EMPTY } from "rxjs";
interface TodoState {
todos: Todo[];
loading: boolean;
}
@Injectable()
export class TodoStore extends ComponentStore<TodoState> {
constructor(private todoService: TodoService) {
super({ todos: [], loading: false });
}
readonly todos$ = this.select((state) => state.todos);
readonly loading$ = this.select((state) => state.loading);
readonly completedCount$ = this.select(
.,
todos.( t.).,
);
addTodo = .( ({
...state,
: [...state., todo],
}));
toggleTodo = .( ({
...state,
: state..(
t. === id ? { ...t, : !t. } : t,
),
}));
loadTodos = .<>(
trigger$.(
( .({ : })),
(
..().(
({
: .({ todos, : }),
: .({ : }),
}),
( ),
),
),
),
);
}
5. Handle Server State with Signals
For HTTP data fetching and optimistic updates.
import { Injectable, signal, inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { toSignal } from "@angular/core/rxjs-interop";
interface ApiState<T> {
data: T | null;
loading: boolean;
error: string | null;
}
@Injectable({ providedIn: "root" })
export class ProductApiService {
private http = inject(HttpClient);
private _state = signal<ApiState<Product[]>>({
data: null,
loading: false,
error: null,
});
readonly products = computed(() => this._state().data ?? []);
readonly loading = computed(() => this._state().loading);
error = ( .().);
(): <> {
..( ({ ...s, : , : }));
{
data = (
..<[]>(),
);
..( ({ ...s, data, : }));
} (e) {
..( ({
...s,
: ,
: ,
}));
}
}
(: ): <> {
previousData = .().;
..( ({
...s,
: s.?.( p. !== id) ?? ,
}));
{
(..());
} {
..( ({ ...s, : previousData }));
}
}
}
6. Migrate from Legacy Patterns
From BehaviorSubject to Signals
@Injectable({ providedIn: "root" })
export class OldUserService {
private userSubject = new BehaviorSubject<User | null>(null);
user$ = this.userSubject.asObservable();
setUser(user: User) {
this.userSubject.next(user);
}
}
@Injectable({ providedIn: "root" })
export class UserService {
private _user = signal<User | null>(null);
readonly user = this._user.asReadonly();
setUser(user: User) {
this._user.set(user);
}
}
Bridging Signals and RxJS
import { toSignal, toObservable } from '@angular/core/rxjs-interop';
@Component({...})
export class ExampleComponent {
private route = inject(ActivatedRoute);
userId = toSignal(
this.route.params.pipe(map(p => p['id'])),
{ initialValue: '' }
);
}
export class DataService {
private filter = signal('');
filter$ = toObservable(this.filter);
filteredData$ = this.filter$.pipe(
debounceTime(300),
switchMap(filter => this.http.get(`/api/data?q=${filter}`))
);
}
Pitfalls
| Anti-Pattern | Instead |
|---|
| Store derived data | Use computed() |
| Mutate signals directly | Use set() or update() |
| Over-globalize state | Keep local when possible |
| Mix RxJS and Signals chaotically | Choose primary, bridge with toSignal/toObservable |
| Subscribe in components for state | Use template with signals |
Verification
- Angular DevTools: Inspect the state tree and signal values to ensure state updates correctly propagate.
- Unit Tests: Write tests for reducers, selectors, and stores to verify state transitions.
- Memory Leaks: Check for lingering subscriptions when using RxJS patterns by ensuring components are destroyed properly.
- Optimistic Updates: Verify that optimistic updates roll back correctly on API failures.
Related skills