Expose Angular Component Logic Using State Reducers

Isaac Mann
InstructorIsaac Mann
Share this video with your friends

Social Share Links

Send Tweet

A component author has no way of knowing which state changes a consumer will want to override, but state reducers handle this problem by allowing the parent component to override any state change.

Instructor: [00:01] This ng template allows the parent component to control what view is displayed based on the state of the toggle component. This toggle component still has some hidden logic that controls how the state is updated, when this toggle function is called.

[00:19] In this case, that logic is just toggling the ON value of the component. We're going to use the State Reducer Pattern to give the parent control over how that state is updated.

[00:31] First, we'll create an interface for the toggle component state. It just has one Boolean ON property. Then, we'll create a type for the toggle state reducer. It's a function that takes the current state which is of type toggle state and it changes object which is a partial value of that toggle state. That will return a new toggle state.

[00:54] This may look familiar to those use Redux, state is your current state, and changes fills the role of the action and it returns a new toggle state. Now, we'll configure our toggle component to take a state reducer as an input that will be of type toggle state reducer.

[01:12] We'll initialize that to a function that takes a state and some changes. It returns a new object with that spreads out the current state and overrides that with the new changes that are passed in.

[01:25] Now, we need to actually use this state reducer. In this set ON state function, we'll create our old state which is just the current ON state. We'll calculate the new state by using the state reducer function with the old state passed in and the new ON value as it changes object.

[01:45] If our state reducer has actually changed the state object, then we will apply the changes with the new state value. Now in order to use this, we'll go to our app component. We'll set the state reducer to our own custom state reducer.

[02:01] Now, let's define that in our TypeScript file. Let's say our app component wants to keep track of the number of times the toggle is clicked. We want to create a state reducer that will stop the button from toggling, if we reach a certain limit.

[02:15] We'll set our state reducer function to be a function that takes the current state and some changes. If the number of times clicked is more than our limit, we'll just return the existing state with no changes. If the ON value has actually being modified, we're going to increment this.times clicked by one.

[02:37] Finally, we'll pass through our changes just like the default state reducer. Now, let's see if this works. We're going to keep clicking and it stopped. Looks like it's working.