State Management in Angular NgRx
Posted By : Arun Rana | 09-Dec-2020
Introduction:
NgRx is a framework for managing the state of the application in an angular app. It comes with tools and libraries to manage both global and local states efficiently in your app. The first question that comes to our mind while hearing about ngrx is "Why do we even need it?"
Requirement:
As an app grows in size it's hard to maintain its state and sharing data between components is one way to solve this problem but then it would require a lot of boilerplate to just maintain a global requirement of even a single variable. We would need to pass the state as component's props inside @Input and if the component has any child then this has to be repeated so that piles up a lot of boilerplate for developers. NgRx has a better approach to this issue, it is needed for managing our state in our web application without the extra clutter. Without it, we would also have to maintain the immutability of the state ourselves but with ngrx, now developers only need to focus on the productive part of the app and ngrx will take care of the state management. As our application grows and we have to look into the various states to update them according to the need/requirement, we also need some helping hand to do it for us depending upon the actions we take to change/modify those states. Managing state is one of the biggest challenges the application will ever face.
Every time you will manipulate the data it will end up with some or other consequences, so to play on the safe side of the road we need ngrx.
Another boon of using ngrx is if a developer migrates from reacting to angular and if the new team has ngrx as the state management tool, so developing with ngrx is somewhat similar to redux so devs don't feel that much resistance towards learning the new framework.
NGRX is an angular/rxjs version of the redux pattern.NGRX is a library to use within an angular application. The “rxjs” part is because of the implementation of ngrx works around an rxjs flow.
How do we change the state of our application is our second concern. So basically now for changing the state of your application, you will need to dispatch an action, without it the state is read-only type. Now actions are the ones that carry the information regarding what is going to be the state after it is being modified.
Also Read: JavaScript Promises vs RxJS Observables
Benefits of using it:
1. This also helps us and make debugging easier.
2. Easily integrate with an angular router.
3. Effects provide easy manipulation of external data interaction between services and the components.
4. Has ngrx store dev tool for an easy visual approach to viewing the app's current state.
Also Read: Building a Redux Application Using Angular
Following is an example to maintain the state of a counter variable in an app.
src/app/counter-state.actions.ts
import { createAction } from '@ngrx/store';
export const incr = createAction('[CounterState Component] Incr');
export const decr = createAction('[CounterState Component] Decr');
export const reset = createAction('[CounterState Component] Reset');
src/app/my-counter/counter-state.html.ts

src/app/my-counter/counter-state.reducer.ts
import { createReducer, on } from '@ngrx/store';
import { incr, decr, reset } from './counter-state.actions';
export const initialState = 0;
const _counterStateReducer = createReducer(
initialState,
on(incr, (state) => state + 1),
on(decr, (state) => state - 1),
on(reset, (state) => 0)
);
export function counterStateReducer(state, action) {
return _counterStateReducer(state, action);
}
src/app/my-counter/my-counter.component.ts
import { Component } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { incr, decr, reset } from '../counter-state.actions'; @Component({ selector: 'app-my-counter', templateUrl: './my-counter.component.html' }) export class MyCounterComponent { count$: Observableconstructor(private store: Store<{ count: number }>) { this.count$ = store.pipe(select('count')); } incr() { this.store.dispatch(incr()); } decr() { this.store.dispatch(decr()); } reset() { this.store.dispatch(reset()); } }
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
//Import these 2 imports
import { StoreModule } from '@ngrx/store';
import { counterStateReducer } from './counter-state.reducer';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, StoreModule.forRoot({ count: counterStateReducer })],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
At Oodles, we provide end-to-end SaaS development services with a focus on building high-quality websites and web applications using JavaScript-based technologies. Our development team is skilled at using Full stack development frameworks including AngularJS and NodeJS to build scalable and responsive web applications for clients. We have completed several Angular and MEAN stack development projects for clients from across the globe.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Arun Rana
Arun is a Frontend Developer. He is a tech enthusiast, and loves to learn new technologies.