Earlier in this newsletter, we saw that calling a method in a component template is an anti-pattern. The antidote to that anti-pattern is to use a pure pipe.
By default, all pipes we use in Angular are pure. Custom pipes are also pure by default. The only way to make a pipe impure is to add the config option pure: false
to its decorator:
What is a pure pipe?
A pure pipe is one that Angular will execute only when there is a pure change to its input value. It is automatically optimized for performance since it is executed only when needed.
A pure change is either a change to a primitive input value (such as string
, number
, or boolean
), or a changed object reference (such as Date
, Array
, or Object
).
In other words, if we consider the following use case:
Here are some examples of pure and impure changes in variables:
With all that information, we are now equipped to call a formatting function in a template by using a pipe (said function would be called in the transform
method of the pipe). We know that the function would run only when the input value changes (purely), which allows us to decide when we want that pipe to be executed again by making either a pure or an impure change to the input value.
Finally, we can double-check that our pipe is working as expected using the Angular profiler to make sure that the pipe doesn’t run more often than expected.