Angular Performance Advice
Avoid Computing Values in the Template
Sometimes in Angular templates, we may be tempted to bind a function in the html template:
getColor()
calls a function to get the color for the background.
Problem: getColor() is constantly getting called during the Angular change detection cycle.
Proof: put a console.log() or breakpoint on your function.
This example shows that the getColor()
function get’s called at least four times. Now image the style is on a table or grid for every single column, or every single cell.
Here the function gets called 95 Times, when it should only get called 24 times.
In our example getColor()
always returns the same value: red.
What we could do is introduce a pure pipe. “ Angular executes a pure pipe only when it detects a pure change to the input value.”
The pipe below takes the value to be transformed, and sets it as the background color.
See the stackblitz link below for the new html implementation, but keep in mind this is just an example. You most likely will be passing in a row number to get odd or even rows, then returning the background color for a zebra colored table.
https://stackblitz.com/edit/angular-fxdwjh?file=src/app/app.component.html
As we expect 24 function calls, we get exactly 24 function calls with this pipe.
Why? because this is a pure pipe, and only detects a pure change to the input value.
Lets add a button, and a No-op click event to both the pipe example, and the bad example that calls a function.
Pipe example: https://stackblitz.com/edit/angular-fxdwjh?file=src/app/app.component.html
What you will notice on the pipe example is when the button is clicked, no extra change detection is firing. We still get the same 24 pure function calls.
Function example: https://stackblitz.com/edit/angular-fxdwjh?file=src/app/app.component.html
In this example, every time anything changes, angular will run the full change detection on the `getColor()` function since it is bound in the template. Just five clicks produces over 380 function calls.
This is only one function on a simple page. Imagine multiple tables on a screen and many clickable actions taking place.