Angular 6 NGXS example – Angular State Management

Angular 6 NGXS example – Angular State Management

NGXS Store is a state management solution for Angular apps that helps us build applications by working around our app’s data (state). In this tutorial, we’re gonna look at how to work with NGXS Store, custom Actions, handle dispatched Actions with @Action and @Select/@Selector decorator. Then we will practice to understand all of them in a simple practical Angular 6 example.

Related Posts:
– NgRx: Angular 6 NgRx Store example – Angular State Management
– State Management with Redux: Introduction to Redux – a simple practical Redux example

– Reactive Streams:

NGXS Store to manage App State

Why we need a State container

State container helps JavaScript applications to manage state.
=> Whenever we wanna read the state, look into only one single place – NGXS Store.
=> Managing the state could be simplified by dealing with simple objects and pure functions.

NGXS Store

Store holds the current state so that we can see it as a single source of truth for our data.
– access state using or @Select/@Selector decorator.
– update state via store.dispatch(action).

@Select() decorator is the way to slice data from the store. We can use it comfortably:


Action is payload of information that is sent to Store using store.dispatch(action).
Action must have a type property that should typically be defined as string constants. It indicates the type of action being performed:

Handle dispatched Actions

NGXS gives us a StateContext object to mutate the store in response to an Action. We don’t need to separate this logic in a Reducer and/or Action stream.

We use getState() to get the current state, setState() to return the state.
In this example, we use patchState() to make updating the state easier: only pass it the properties we wanna update on the state and it handles the rest.


Example overview


This is a simple Angular 6 NGXS Application that has:
CustomerStateModel (customer.state.ts) as the main state that is stored inside NGXS Store.
– 2 types of Action: CREATE_CUSTOMER and DELETE_CUSTOMER (customer.actions.ts).
– Dispatched Actions will be handled with @Action decorator (customer.state.ts).

We can save/remove Customer. App will update UI immediately.


>> Click on Delete button from any Customer:


Step by step

Install NGXS Store

Run cmd: npm install @ngxs/store.

Create Data Model


Create Actions


Create State & handle dispatched Action


Import NGXS Store


Create Components
Create Customer Component



Customer Details Component



Customers List Component



Import Components to App Component



Source Code


By grokonez | August 24, 2018.

Last updated on April 30, 2019.

Related Posts

1 thought on “Angular 6 NGXS example – Angular State Management”

Got Something To Say:

Your email address will not be published. Required fields are marked *