// Tutorial //

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

Published on May 11, 2017
Default avatar

By Alligator.io

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

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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;
}

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';

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;
  }

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Learn more ->
DigitalOcean Cloud Control Panel