Last Updated: October 20, 2020
· lauranutt088

State Management in Angular using NGXS

Definition of State:
The handling of the data states is very complicated in the bigger apps. Each component has its own angular state to share the data / state between the components that we usually use @Input and @Output decorators, but it is difficult to maintain data consistency as the framework goes larger. So, Redux was introduced to solve this problem. It offers a central store that houses the application in all states. The stored state can be accessed by each component without sending it from one component to another.

Ok, what is NGXS?
A state management pattern + library is NGXS. It offers the state of your application as a single source of reality, providing basic rules for predictable mutations in the state.

NGXS is modelled after the popularly implemented CQRS pattern in libraries such as Redux and NgRx, but by using modern TypeScript features such as classes and decorators, it eliminates boilerplate.

Implementation of NGXS:
Compared to other state management patterns such as reducex and Akita, NGXS is very easy to use. NGXS over the redux pattern takes full advantage of angular and typescript. NGXSS has 4 main principles.

  1. Store: It is a global state container and handles the application states. In order to execute those operations, we should dispatch the activities. TodoActions.AddTodo(form));

  2. Action: An action is a kind of command that should be called when something happens or you want to trigger something like adding a new todo, listing todos, etc. at some case.
    export class AddTodo {
    static readonly type = '[Todo] Add';
    constructor(public payload: ITodo) { }

  3. State: To define metadata and action mappings, states are classes along with decorators.
    import { Injectable } from '@angular/core';
    import { State } from '@ngxs/store';

name: 'todoList',
defaults: {
todoList: [],
export class TodoState {}

  1. Select: Selects are functions that slice a particular portion of the state from the container of the global state , i.e. to get the data whenever you want to use from the particular global state. @Select(TodoState) todoList$: Observable<ITodo>;

This was a walkthrough some of the basic concepts of NGXS. I hope they would be useful