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

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

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http

GraphQL API Integration In Asp.Net Core Application

Introduction: GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data. How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions. HTTP-POST is the only Http verb recommended by the GraphQL. The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API: The main building blocks of GraphQL API is Schemas and Types.  A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc. T