Sharing Top Content from the Angular-sphere.

Using @ngrx/entity in Angular to Simplify Store Reducers

Using @ngrx/entity in Angular to Simplify Store Reducers

  • With @ngrx/entity, resources are known as entities (e.g.: users, todos, tickets, …) and we can create entity adapters that have built-in methods for CRUD reducer actions (create, read, update, delete).
  • We’ll demonstrate how to use @ngrx/entity in this post via a simple todo app example, very similar to the one we implemented in our intro to @ngrx/store.
  • Here’s our todo model interface: – – And our 4 possible actions for todos are defined like the following with distinct classes that implement @ngrx/store’s Action interface: – – These actions will stay exactly the same when using @ngrx/entity.
  • You can install it in our project like this: – – And the final piece is the component’s template, which can look a little bit like this: – – 🎉 Now our todo app is working and properly using @ngrx/store for state management.
  • Our app module changes a little bit to include a reducer map called reducers that we’ll define in a little bit that’s passed-in to StoreModule’s forRoot method: – – Now for our todo reducer, we change it to something like the following.

Let’s build a simple Angular 4 todo app and make use of @ngrx/store as well as the new @ngrx/entity to simplify our reducer.

Redux and @ngrx/store reducers for CRUD operations often have a similar shape and end up being mostly boilerplate code. To help simplify and cut on the boilerplate, the ngrx organization created a new library called @ngrx/entity that can used with @ngrx/store in Angular 2+ projects. With @ngrx/entity, resources are known as entities (e.g.: users, todos, tickets, …) and we can create entity adapters that have built-in methods for CRUD reducer actions (create, read, update, delete).

We’ll demonstrate how to use @ngrx/entity in this post via a simple todo app example, very similar to the one we implemented in our intro to @ngrx/store.

First, let’s see how we would implement the todo app without @ngrx/entity. Here’s our todo model interface:

And our 4 possible actions for todos are defined like the following with distinct classes that implement @ngrx/store’s Action interface:

These actions will stay exactly the same when using @ngrx/entity.

Our todo reducer looks like this:

Notice how our reducer contains all the boilerplate for adding, updating, toggling and deleting todo items. This is where @ngrx/entity will be especially helpful.

Here’s how our app component looks like, selecting the todos from the store and dispatching actions:

We make use of a small utility called angular2-uuid to create a unique ID for our todos. You can install it in our project like this:

And the final piece is the component’s template, which can look…

Using @ngrx/entity in Angular to Simplify Store Reducers

Comments are closed, but trackbacks and pingbacks are open.