Goodbye Getter, Hello Signals

Use Angular 16 Signals to Avoid a Common Code Review Catch

Kevin Longmuir
HeroDevs

--

Nonspecific coding screen with HeroDevs color gradient

Angular 16 introduced Signals, an all-new reactive primitive designed to improve the way we as Angular developers deal with reactive programming. Signal is a powerful new data type, with lots of exciting possibilities. At ng-conf 2023, I learned about Signals firsthand from the Angular core team and some of the best minds in the Angular community. As they spoke about Signals, I saw an opportunity to change the way I code, specifically with a TypeScript feature that I always find myself needing, but always gets pointed out as a no-no in code review.

Let’s see how Signals can fix the dreaded “binding to a function in the template” critique once and for all.

Don’t Bind to a Function

You may have seen this sentiment on the internet, or in one of your code reviews. “Do not bind to a function in your component template!” That person is not just being a stickler, there’s a very good reason not to bind to function calls in your template: app performance suffers. Here is an example of a function being used in a data binding:

<button type="button" [disabled]="isButtonDisabled()">
Click Me
</button>

This type of binding will work. This will evaluate the function as you wrote it and Angular will receive the value properly. However, using a function has some downsides with how Angular’s change detection works. Angular uses change detection to determine what bound template values have changed and then updates the DOM accordingly only for the values that have changed. This optimizes performance by making as few changes to the DOM as possible.

The problem is, Angular has no way of knowing if values used inside a function have changed. It knows that you are calling this function, but it does not know the contents of the function. Because of this, Angular will run this function on every change detection cycle to make sure the function result is updated. Even if a totally unrelated value changes, this function is getting run. This might be acceptable for simple functions, but if your function does things like array iteration or object creation, these multiple calls can get expensive very quickly.

Continue Reading on HeroDevs Blog: For the full article and more in-depth insights, visit our official blog. Click here to read the complete post on HeroDevs.

About HeroDevs

HeroDevs is a software engineering and consulting studio that specializes in front-end development. Our team has authored or co-authored projects like the Angular CLI, Angular Universal, Scully, XLTS — extended long-term support for AngularJS, Vue 2, and many others. We work with fast-growing startups and some of the world’s largest companies like Google, GE, Capital One, Experian, T-Mobile, Corteva, and others. Learn more about us at herodevs.com.

--

--