Angular NgRx Boilerplate Reduction

John Youngers
Youngers Consulting
2 min readDec 19, 2017

UPDATE: most of this content is no longer applicable as of the newer versions of NgRx; please see the 2019 version of this article:

In our Angular 5.x application currently in development, we recently started converting over information and logic regarding the state of the application to a redux pattern via NgRx.

Although the pattern is clean and easy to implement, it didn’t take long before the sheer amount of boilerplate required to do even the simplest task started to make me question whether this was the best option.

For example, a new feature generally requires:

On top of those 5 steps, you then would need to test the reducer to validate it’s doing what it should be doing per action, including returning an unaltered state if the action was not related to this feature.

Adding another action down the line would require steps 1, 2, 3, 5(and likely the remaining step regarding the state) to be revisited.

My goal was to take advantage of the object oriented features of TypeScript to see if we could reduce the amount of code required to setup a new feature (without breaking existing compatibility with NgRx and the Redux browser tool extensions), and this is what I came up with:

With these changes we’ve reduced the step count by 1, but more importantly if we need to add a new action in the feature, all we need to do is create the new action class (and likely update the state interface and initial state).

Testing should be very similar; however, we no longer need to verify our reducer ignores unrelated actions (which would be tested in redux.spec.ts).

Since we’re no longer defining constants for the action type strings, if you’re using the effects library, you’d need to make the following change:

I haven’t noticed any issues yet with this approach, but I’d be open to any thoughts regarding this methodology before we get too far into the weeds: I’m sure there’s a cleaner way to set some of this up.

Conceptually we’ve drifted a bit since the state of the action object impacts the reduce() method, but to me it seems like a reasonable trade-off in order to cut down on code.

--

--