Anti-pattern series: Calling a method in a template

If you’re calling a method/function in the HTML template of any of your components, try the following experiment: Add a console.log("here") inside that method.

Then, interact with your application by clicking around, entering information in a form, etc. What you’ll see in your console is something like this:

Why is this happening? Angular’s change detection runs every time an event occurs in the browser. Zone.js tells Angular that “something happened” when we interact with an Angular application. Then, Angular checks its component tree for updates. If you’re using methods in your HTML templates, the only way for Angular to see if the output of that method has changed is to… call it again.

As a result, using methods in your HTML templates is not recommended. Doing so can impact performance negatively. Instead, use bindings to class properties as follows:

Before:

After:

Note that if you need to call a method/function to perform some formatting, you should create a custom pipe. Pipes are designed to run only when their input data changes, which means they are optimized for best performance by default.

You can take a look at an example here on Stackblitz. I added a console.log("here") inside my custom pipe to showcase that it runs only once:

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.