State Management in Angular: NgRx vs Services 🔄
Managing state in an Angular application can become complex as your app grows. Angular provides multiple ways to handle state: using services or the NgRx library for more advanced state management.
Using Services for State Management 🛠️
In small or simple applications, you can manage state using Angular services. Services act as singletons, meaning the same instance of a service is shared across your application. Here’s an example:
@Injectable({
providedIn: 'root',
})
export class CounterService {
private counter = 0;
increment() {
this.counter++;
}
getCounter() {
return this.counter;
}
}In this example, the service holds and manages the state of a simple counter.
NgRx for Advanced State Management 📦
For more complex applications, NgRx is a powerful library based on Redux that provides a more structured way to manage application state. It uses actions, reducers, and stores to manage state changes.
Get Marcelo Domingues’s stories in your inbox
Join Medium for free to get updates from this writer.
Example of a basic NgRx setup:
Define Actions:
export const increment = createAction('[Counter Component] Increment');Create a Reducer:
export const counterReducer = createReducer(0,
on(increment, (state) => state + 1)
);Access the Store:
this.store.select('counter').subscribe(count => {
this.counter = count;
});Conclusion
Use services for simple state management and NgRx when your application grows more complex, especially when you need to manage shared state across many components. 🔧








