Skip to main content

Angular State Management With NgRx


NgRx framework helps Angular to develop more reactive applications. NgRx provides state management to an application, where data of an application is stored at a single place and then supplied throughout the application where ever needed. Using NgRx if data is updated, all the components consuming that data get updated instantly.

Benefits of using NgRx with Angular application like Serializability, Type Safety, Encapsulation, Testable, and Performance.

Key Features:

NgRx framework key features like

  • Store: A store is a data place where all the application related information stored and supplied to the Angular components on demand.
  • Reducer: A reducer is a pure function based on Actions it returns the new state.
  • Actions: An action expresses an event of an application, that causes a change in the state of the application.
  • Selector: A selector is a pure function that obtains a slice of data from the store.
  • Effects: An Effect is to isolate components from using services(APIs) and with the help actions and reducers change the state of the store.
Note: NgRx store version 8+ using in this sample, there are some new features are added and implementation style was changed from v8+ when compare to v7 and below.

Create An Angular Project:

Let's create a sample to show items in a Bakery Shop. So first create the angular project using Angular CLI commands. Click here for Angular CLI commands.

Install @ngrx/store:

Open the command prompt by taking package.json file in the sample project physical location as a reference path. Now to use NgRx framework run the following NPM command
               "npm install @ngrx/store --save"
Now in a package.json observe as below


NgRx Actions represents the event expression of an application. It represents what to happen and how to happen the changes in an application. Based on Action dispatches NgRx Store or NgRx Effects get triggered.
export interface Action {
    type: string;
NgRx Action is a simple interface having only one property 'type', this 'type' property is like a name or identification or role of that particular NgRx Action. Since it is an interface we need to implement it to use it. But Ngrx Store provides the predefined function to create and use NgRx action.
import {createAction} from '@ngrx/store';

export const getStudents = createAction(
    '[Student] load all students'
  • Here 'createAction' is a predefined function provided by the NgRx Store and it is an overloaded function. 
  • The parameter passed to 'createAction' is a 'type' property of the action, if we observe from the type property this action will trigger an event to load all students from API or NgRx Store.
  • '[Student]' this just namespace or naming convention to represent the NgRx Action type.

import {createAction ,props} from '@ngrx/store';

export const getNewsByRange = createAction(
    '[News] load news by date values',
    props<{startDate:string, endDate:string}>()
  • Here 'createAction' is another overloaded function with two parameters. 
  • 'props<T>()' is a function defined by NgRx Store, this function gives the possibility to pass query parameters of action.
  • In the above action method, it represents the loading of news information with specified date ranges as a query filter to the news data

Create Actions:

Our sample application to show bakery items, let us start code to display cakes in a bakery. Now create folder name as 'store', then create another folder named 'cakes' and now create an action file name as cake.action.ts in the 'store/cakes/' folder.
cakes.action.ts :
import {createAction} from '@ngrx/store';
export const loadCakes = createAction(
    '[Cakes] load'
Here action represents to load all cakes.


Reducer is a pure function their goal is like the same output every time for the given input. Reducers take two input params like Action and State. 'State' is just a JSON object which stores the data and based on the action type reducer returns the new state to the angular components. This Reducer gets invoked by the store dispatch which will discuss in later.

import {Action, createReducer, on,createAction} from '@ngrx/store';
const loadSomething = createAction(
export interface State {

export const initialState: State = {

const loadReducer = createReducer(initialState,
    on(loadSomething,state => {
        const newState =state;;
        return state;

export function reducer(state: State| undefined,action :Action){
    return loadReducer(state, action);
  • 'State' can be imagined as a database in the serverside language. It is to store and deliver the data on demand.
  • 'initialState' is like default empty state at the time no data exist in the store.
  • Reducer function takes state and action as input params. In version 7 or below inside reducer we wrote code like switch case with return new state, but from NgRx v8+ we returning 'createReducer' function which takes two parameters like state and function. 
  • In 'createReducer' second parameter is an arrow function where we can write logic to create a new state and give it back to the application.
  • The reason we always create a new state and return, due Redux(NgRx framework build on top of Redux) principals that reducers are a pure function that is immutable and only return a new state.

Create a Cake Model and Cake State Model:

Models make coding good by providing 'TypeSafety' to it, so whenever possible where ever needed alway create models. Now in this sample, let us create the folder 'model' and inside add files like 'model.ts' which contains all application-related models and 'store.model.ts' which contains all NgRx Store, related models.

export interface Cake{
import {Cake} from './model'
export interface CakeState {

Create Reducer:

Create a file at 'stores/cakes' and name as 'cakes.reducer.ts'

import { Action, createReducer, on } from "@ngrx/store";
import {loadCakes} from './cakes.action';

import { CakeState } from "../../models/stores.model";

export const initialState:CakeState ={
  Data : [],
  SuccessMessage : '',
  ErrorMessage: ''

const cakeReducer = createReducer(
    on(loadCakes, state => {
        return {

export function reducer(state: CakeState | undefined, action: Action){
    return cakeReducer(state, action);
  • Here 'initialState' is like default state. 
  • 'cakeReducer' is 'createReducer' function here we taking the first parameter as 'State' and the second parameter is 'on' function provided by NgRxStore. 
  • 'on' function overloaded function here we are taking the first parameter action 'loadCake' and the second parameter is arrow function where the state as input parameter here we can create new state using current state and return the state(later steps we will update this 'cakeReducers' with the different set Actions).


Selectors are also pure functions used to get a slice of data from the NgRx store. Selectors represent query methods. Using selectors it isolates or avoids writing data filtering or data modification code in the angular components.
import {createFeatureSelector, createSelector} from '@ngrx/store'
export interface BookState{
    Name: string,
export interface OrdersState {
export interface AppState{

export const selectBooks = createFeatureSelector<appstate,Bookstate>('books');
export const selectOrders = createFeatureSelector<appstate,ordersstate>('orders');

export const selectBookName = createSelector(selectBooks, state => state.Name);
export const selectOrderId = createSelector(selectOrders, state => state.Id);
  • In the above example 'BookState', 'OrderState' represents two different stores. 
  • In general, all the store states are maintained under one state can name as 'AppState'(can be called as the application state).
  • NgRx provides 'createFeatureSelector' it gives a particular state in an application based input parameter. 
  • 'createFeatureSelect' expects the string parameter whose value need to exactly match with 'AppState' property name like 'books' and 'orders'.
  •  Here 'selectBooks' represents 'BookState' and 'selectOrders' represents 'OrderState'. 
  • NgRx provides 'createSelector' gets inside data of an 'State'. Here 'selectBookName' represents a collection of book name and 'selectOrders' represents a collection of order ids.

Create Selectors:

Create a file for selectors at a path '/stores' and name the file as 'store.selectors.ts'

import {createFeatureSelector, createSelector} from '@ngrx/store'
import { CakeState } from "../models/stores.model";
export interface AppState {

export const selectCakeState = createFeatureSelector<appstate,cakestate>('cake');

export const selectAllCakes = createSelector(selectCakeSate, state => state.Data);
  • Here we have created 'AppState' which encapsulates all other States in the application. 'selectCakeState' holds the 'CakeState' with the help 'createFeatureSelector'. 'createFeatureSelector' takes 'cake' as input parameter, this 'cake' string should match with property name 'AppState'.
  • 'selectAllCakes' is a state which represents a collection of 'Cake' with the help of 'createSelector' provided by NgRx Store 

Create A Service:

Now in the 'assets' folder add a new file name as cake.json in that file mock some cake items. In real-time we are going to consume API instead of a mock JSON file
Create a service folder as 'app/services' in that add a new file 'cake.service.ts'. It is an injectable service that calls cakes.json file using angular Httpclient.

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

import{map} from "rxjs/operators";

export class CakeService {
  constructor(private http: HttpClient) {}

     return this.http.get("./assets/cakes.json").pipe(map(data=> data["AllCakes"]))


In an Angular Application creates injectable services to consume APIs. We access those services by injecting them into our components to display the data from API. Instead of injecting services into the components we can achieve the same functionality by using NgRx Effects. By using the Effects we can isolate services from components.

Effects are like events that occur out of the application and are not consumed by components directly like we do for services. Effects are triggered based on action dispatched from the store, once the effect gets activated it calls API and pushes the data to the store.
import {Injectable} from '@angular/core';
import {Actions,createEffect, ofType} from '@ngrx/effects';
import {of} from 'rxjs'
import {mergeMap, map, catchError} from 'rxjs/operators'

export class SomeEffects{
  constructor(private actions$:Actions){


  loadSomething$ = createEffect(() => 
          ofType('[Something] load Something'),
          mergeMap(() => of('In real time here api call observable will be used')
              map(data => ({type:'[Something] load Something Successfully',payload:data})),
              catchError(() => of({type:'[Something] load Something Failed'}))
  • 'createEffect' is provided by the NgRx store to create an effect like 'loadSomething$'. 'createEffect' takes a function as an input parameter, this input parameter function returns observable. 
  • 'Actions' is provided by the NgRx Effects. 'Actions' is an observable type, it gets invoked on every action dispatched from the store in angular components. 
  • 'Actions' are injected into effects services, since it is observable here we listen to the action using 'pipe' operator. 'OfType' in NgRx Effects filters the action by matching the action type  (like '[Something] load Something') with the action type dispatched from the store, if both types of actions match effects goes further execution else effect will be stoped. This says 'OfType' helps to execute the appropriate Effects. 
  • Then listen to the inner observable of API call inside of 'mergeMap' RXJS operators. Finally on the successful execution of inner observable returns observable object of action type and payload data or if inner observable fails returns observable object of an action. This observable result will be available to the NgRx store for changing its state.

Install Effects:

Ngrx shifts effects separate package so run the following command
            npm install @ngrx/effects --save

Create An Effect:

Now add Effects file in 'src/stores/cakes/' and name as 'cakes.effects.ts'

import { Injectable } from "@angular/core";
import { Actions, createEffect, ofType } from "@ngrx/effects";
import { of } from "rxjs";
import { mergeMap, map, catchError } from "rxjs/operators";
import { CakeService } from "../../services/cake.service";

export class SomeEffects {
  constructor(private actions$: Actions, private cakeService:CakeService) {}

  loadCakes$ = createEffect(() =>
      ofType('[Cakes] load'),
      mergeMap( () => this.cakeService.get()
          map(data => ({type:'[Cakes] successful cakes load',cakes:data})),
          catchError(eror => of({type:'[Cakes] fails cakes load'}))
  • 'Actions' from NgRx effects and CakeService are injected into this effects service. 
  • 'loadCakes$' creates an effect using 'createEffect()'. 'ofType('[Cakes] load')' it represent this effect only triggered for '[Cakes] load' action. 
  • On successful API call return Observable of the object literal with keys like 'type' and 'cake'  (this 'cakes' name should match with the action props method like props<{cakes: Cake[]}>). On failed API call return Observable of the object literal with key 'type'. This Observable object will be passed to the store based on action types passed in the key 'type' and then the store creates a new state.

Create Actions For API Success And Fail:

In previous steps, we have created the '[Cakes] load' action. Now we need to update the 'cakes.action.ts' file with 2 more actions

export const successCakeLoad = createAction(
    '[Cakes] successful cakes load',

export const failsCakeLoad = createAction(
    '[Cakes] fails cakes load'

Update Reducer To Change Store State Based On API Success Or Fail Actions:

Now update the 'cake.reducer.ts' which changes the state of the store based on the action methods.

import { Action, createReducer, on } from "@ngrx/store";
import * as cakesAction from './cakes.action';

import { CakeState } from "../../models/stores.model";

export const initialState:CakeState ={
  Data : [],
  SuccessMessage : '',
  ErrorMessage: ''

const cakeReducer = createReducer(
        (state, {cakes}) => {
            return {
                Data : cakes,
                SuccessMessage : 'Success',
        state => {
            return {

export function reducer(state: CakeState | undefined, action: Action){
    return cakeReducer(state, action);

  • On 'cakeAction.successCakeLoad' action represents API success, here create a new state with the payload from the API and SuccessMessage property update with some success message
  • On 'cakeAction.failsCakeLoad' action represents API fails, here create new state with empty data and ErrorMessage property updated with some error message

Access Data From NgRx Store:

Let save API data to store and access it from the angular component. Now create a new component at 'src/cakes' and name as cakes.component.ts

import {Component, OnInit} from '@angular/core';
import {Store, select} from '@ngrx/store';

import {CakeState} from '../models/stores.model'
import * as cakeActions from '../stores/cakes/cakes.action';
import * as storeSelectors from '../stores/store.selectors';
import {Cake} from '../models/model'

export class CakeComponent implements OnInit {
    constructor(private store:Store<storeSelectors.AppState>){

    ngOnInit(){ => {
            this.allCakes = data;
  • In the constructor inject store like 'Store<storeSelectors.AppState>', by doing this we have access to the store with all states that are used in the application this happened because store type is 'AppState'.
  • AppState is an application state which holds all other individual stores states. In our application, we created only one state 'CakeState', which resides inside the 'AppState'.
  • In ngOnInit, we dispatch the action 'cakeActions.loadCakes()'. In an application on dispatching an action will automatically trigger all the 'NgRx Effects' get invoked, but the only Effect gets executed which matches the action dispatched. If we recall the above steps we have created NgRx Effect with action name 'loadCakes'.
  • In ngOnInit, we registered a store subscription with the NgRx Selector 'selectAllCakes'. This subscription gets invoked on every update of the store. Herewith 'selecAllCakes' selector going to query all the cakes from the store.
Now create 'cake.component.html' to display  our cakes:
<h1>Cake Bite</h1>

<div class="row">
    <div class="col col-sm-4" *ngFor="let cake of allCakes">
        <div class="card">
            <img src="/assets/{{cake.Image}}" class="card-img-top" alt="">
        <div class="card-body">
           <h5 class="card-title">{{cake.CakeName}}</h5>
           <div class="row">
             <div class="col col-sm-6">
             <div class="col col-sm-6">
                $ {{cake.Cost}}

Update NgRx Store & NgRx Effects Module In AppMoudle:

Final step update NgRx Store and NgRx Effects modules in AppModule file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {StoreModule} from '@ngrx/store';
import {EffectsModule} from '@ngrx/effects';
import {HttpClientModule} from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {CakeComponent} from './cakes/cake.component';
import * as cakeReducer from './stores/cakes/cakes.reducer';
import {CakeEffects} from './stores/cakes/cakes.effect';
import {CakeService} from './services/cake.service';

  declarations: [
  imports: [
  providers: [CakeService],
  bootstrap: [AppComponent]
export class AppModule { }
  • 'StoreModule.forRoot({})' is NgRx Store modules, we need to register all our application reducer function like key-value pair object in the module
  • 'EffectsModule.forRoot([])' is NgRx Effects modules, we need to register all our application effects like an array of objects in the module.

Test Sample Application:


A successful sample application was created using NgRx Store. Using the NgRx Store Statemangement of an application becomes a very essay. Since NgRx Effects isolate services from the angular component, it makes angular components very lightweight and logic free. Data sharing between components will become very flexible.



Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti