Getting Started With ngrx for Redux-Style State Management in Angular

The Redux pattern is a very powerful way to manage state in web apps, especially when the application gets more complicated. Redux the library is most often used with React, but thanks to the ngrx/store library, combined with the power of RxJS, we can manage our app’s state in a Redux-like fashion in Angular apps.

Here a quick refresher on the 3 basic principles of Redux:

  • The whole state of the app is stored in a single state tree.
  • The state is read-only.
  • State changes are made through reducers that use only pure functions (functions that don’t mutate objects, but return completely new objects instead).

See the official docs for a more in-depth look at Redux.

This post has been updated to be compatible with ngrx 4+. You'll need TypeScript 2.4+ and RxJS 5.4+.


In this post we’ll build a very simple todo app that let’s us add, remove and update todos as well as mark todos as completed.

Getting Started

First, you’ll need ngrx/store, which can be installed in your project with npm or Yarn:

# npm
npm install @ngrx/store --save

# Yarn
yarn add @ngrx/store

Our Todo Reducer

Now let’s go ahead and create a simple reducer for our todo app. If you’ve written reducers before this will be familiar:

reducers/todo.reducer.ts

import { Action } from '@ngrx/store';

export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export const UPDATE_TODO = 'UPDATE_TODO';
export const TOGGLE_DONE = 'TOGGLE_DONE';

export interface ActionWithPayload<T> extends Action {
  payload: T;
}

export interface TodoPayload {
  index?: number;
  done?: boolean;
  value?: string;
  newValue?: string;
}

export function todoReducer(state = [], action: ActionWithPayload<TodoPayload>) {
  switch (action.type) {
    case ADD_TODO:
      return [action.payload, ...state];
    case DELETE_TODO:
      return state.filter((item, index) => index !== action.payload.index);
    case UPDATE_TODO:
      return state.map((item, index) => {
        return index === action.payload.index
          ? Object.assign({}, item, { value: action.payload.newValue })
          : item;
      });
    case TOGGLE_DONE:
      return state.map((item, index) => {
        return index === action.payload.index
          ? Object.assign({}, item, { done: !action.payload.done })
          : item;
      });
    default:
      return state;
  }
}

Actions have a type and an optional payload. The type should be a string, so here we define and export constants that hold our different types. The reducer function itself takes a state and an action and then uses a switch statement to return the correct state depending on the action type.

Our switch statement defines a default clause that just returns the state in case the action provided doesn’t match any of our predefined actions.

Notice how, in the switch statement, our operations always return a new state instead of mutating the current state.

Configuring the App Module

Now that we have our reducer in place, we can configure the app module with the ngrx/store module and our reducer:

app.module.ts

// ...

import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { todoReducer } from './reducers/todo.reducer';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    // ...
    StoreModule.forRoot({ todoReducer })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We import StoreModule and then add it to our NgModule’s imports using the provideStore method and the name of our reducer.

Selecting and Dispatching in the Component

Now that we have our reducer in place and our app module properly configured, we can inject ngrx’s Store service into our components. Then it’s as simple as using the Store service to select our data and to dispatch actions.

When selecting data with Store.select, the return value is an observable, which allows us to use the async pipe in the template to manage our subscription to the data.

Here’s our component class implementation, we a few important items highlited:

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { Store } from '@ngrx/store';
import { ADD_TODO, DELETE_TODO, UPDATE_TODO, TOGGLE_DONE }
  from './reducers/todo.reducer';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [
    `.done { text-decoration: line-through; color: salmon; }`
    ]
})
export class AppComponent implements OnInit {
  todos$: Observable<any>;
  todo: string;
  editing = false;
  indexToEdit: number | null;

  constructor(private store: Store<any>) {}

  ngOnInit() {
    this.todos$ = this.store.select('todoReducer');
  }

  addTodo(value) {
    this.store.dispatch({ type: ADD_TODO, payload: { value, done: false } });
    this.todo = '';
  }
  deleteTodo(index) {
    this.store.dispatch({ type: DELETE_TODO, payload: { index } });
  }

  editTodo(todo, index) {
    this.editing = true;
    this.todo = todo.value;
    this.indexToEdit = index;
  }

  cancelEdit() {
    this.editing = false;
    this.todo = '';
    this.indexToEdit = null;
  }

  updateTodo(updatedTodo) {
    this.store.dispatch({ type: UPDATE_TODO, payload: { index: this.indexToEdit, newValue: updatedTodo } });
    this.todo = '';
    this.indexToEdit = null;
    this.editing = false;
  }

  toggleDone(todo, index) {
    this.store.dispatch({ type: TOGGLE_DONE, payload: { index, done: todo.done } });
  }
}

You can see that our component class is quite simple and most of what it does is dispatch actions to the store.

Component template

The component template is as simple as it gets:

<input placeholder="your todo" [(ngModel)]="todo">

<button
  (click)="addTodo(todo)"
  [disabled]="!todo"
  *ngIf="!editing">
    Add todo
</button>

<button
  (click)="updateTodo(todo)"
  *ngIf="editing">
    Update
</button>
<button
  (click)="cancelEdit()"
  *ngIf="editing">
    Cancel
</button>


<ul>
  <li *ngFor="let todo of todos$ | async; let i = index;">
    <span [class.done]="todo.done">{{ todo.value }}</span>
    <button (click)="editTodo(todo, i)">Edit</button>
    <button (click)="toggleDone(todo, i)">Toggle Done</button>
    <button (click)="deleteTodo(i)">X</button>
  </li>
</ul>

🍰 And there you have it! A very simple, but functional todo app powered with Redux-style state management, thanks to ngrx/store.

✖ Clear

🕵 Search Results

🔎 Searching...