Signals custom equality functions

Angular Signals are growing almost every day with new features and new ways of building Angular applications. If you’re still unsure about signals and want to catch up, you can watch this Angular Signals workshop recording on Youtube or sign up for my continuously updated Angular Signals course.

Today, let’s explore how Angular determines if the value of a signal has changed. If we create the following signal with a default value of “Hello”:

Then calling name.set("Hello") does not trigger any updates for any of the consumers of our name signal. That’s because Angular compares the “new” value with the previous one using a === comparison, and "Hello" === "Hello" is true, so Angular doesn’t trigger any change.

What about objects? When comparing objects with ===, we’re comparing references, meaning “Are the two variables pointing at the same object?” We can verify that easily with a few lines of Javascript running in a browser console:

This leads us to the custom signal equality function. If we want to do a deep comparison instead of just comparing references, we can instruct Angular to do so by providing our own comparison function. Here is the example used by the Angular team:

Of course, we don’t need lodash to implement custom equality functions. For example, we want to create a signal that only emits updates when the current user ID changes. We don’t care if the user’s name or email changes, just the ID (which would indicate that a new user logged in, most likely):

With this approach, the signal doesn’t trigger any updates if we change values that aren’t the ID. For instance, we can secretly turn our user into Batman (and note that I do create a new object by making a copy of the current one, which would make === return false):

And yet my user remains known as Bruce after turning him into Batman (full example here on Stackblitz):

Why use custom equality functions?

Performance could be one thing: if we have a signal that stores an object and know that the only change we make to that object is one or two specific properties, then creating a custom equality function on these properties would make perfect sense. Even more so if the properties are in nested objects, though I wouldn’t recommend using deeply nested objects as signal values, keeping our values as flat as possible instead.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.