Angular — State Management
State Management Options
| Method | Complexity | Best For |
|---|---|---|
| Component | Low | Local state |
| Service | Medium | Shared state |
| Signals | Medium | Reactive state |
| NgRx | High | Complex apps |
Service Pattern
@Injectable({ providedIn: 'root' })
export class TodoService {
private todos = new BehaviorSubject<Todo[]>([]);
todos$ = this.todos.asObservable();
addTodo(text: string) {
const current = this.todos.value;
this.todos.next([...current, { id: Date.now(), text, completed: false }]);
}
toggleTodo(id: number) {
const current = this.todos.value;
this.todos.next(current.map(t =>
t.id === id ? { ...t, completed: !t.completed } : t
));
}
}
Signal Store (NgRx)
import { signalStore, withState, withMethods, patchState } from '@ngrx/signals';
export const TodoStore = signalStore(
withState({ todos: [] as Todo[] }),
withMethods((store) => ({
addTodo(text: string) {
patchState(store, {
todos: [...store.todos(), { id: Date.now(), text, completed: false }]
});
},
toggleTodo(id: number) {
patchState(store, {
todos: store.todos().map(t =>
t.id === id ? { ...t, completed: !t.completed } : t
)
});
}
}))
);
Mini Practice
- Create a state service
- Use BehaviorSubject
- Create a signal store
- Compare patterns
Up Next
Continue with SSR — server-side rendering.
Related Topics
Frequently Asked Questions about State Management
What is State Management in Angular?
State Management is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn State Management?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn State Management.
Why is State Management important in Angular?
State Management is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.