📢 Getting to Know Angular Differs
Angular differs are probably the least known APIs; These are highly optimized building blocks used by Angular itself throughout the framework (ngClass, ngStyle, ngFor, etc.).
You certainly won’t use them on a daily basis, however, given the right circumstances, they can prove to be very useful. If you ever get to the point where you’re saying to yourself:
It’s not enough for me to know that something has changed, I want to know what has changed.
Then you should know that Angular differs is the answer.
Angular offers two types of differs APIs, one is the IterableDiffer
and the second is the KeyValueDiffers
.
The IterableDiffer API
IterableDiffer
is an API that tracks changes made to an iterable over time and also exposes an API enabling you to react to these changes.
Let’s learn how we can use it by creating our own ngClass
directive.
The find()
method checks whether Angular has a differ that supports the type of the given parameter. We can examine this process in the source code:
Once found, the create()
method returns an instance of this differ, in this case DefaultKeyValueDiffer
.
Great, we have a differ. Now let’s see how we can use it. Our goal is to listen for any change in the ngMyClass
input, and based on that adding or removing the class.
We can check for changes by calling the diff()
method with the new value.
When there aren’t any changes the return value will be null, otherwise the return value will be an object that exposes self-explanatory methods that we can use to react to these changes.
In our case, we want to know whether an item was added or removed so we can act accordingly.
The KeyValueDiffers API
The KeyValueDiffers
api works in a similar matter, except it tracks the changes in an object rather than an iterable.
The same concepts mentioned in the first section also apply here. Let’s change the directive we created to get an object instead of an array:
When using KeyValueDiffers
the find()
and create()
method implementations are the following:
Now that we have a differ, let’s use it:
Same as before. When we don’t get null, we have handy self-explanatory methods that give us all what we need.
Follow me on Medium or Twitter to read more about Angular, Vue and JS!
Things to not miss: