Tutorial hero
Lesson icon

Using Angular Pipes

Originally published August 25, 2022 Time 2 mins

It’s very easy and convenient to make a function call from an Angular template like this:

template function pipe

But maybe you have heard that you’re not really supposed to do this for performance reasons. The reason calling functions from your template is a potential performance concern is that every time change detection is triggered, your template is going to be re-evaluated, and any function calls from your template are going to need to be re-run.

The performance impact of this will depend on exactly what it is your functions are doing. Regardless of whether the impact is big or small, there usually isn’t a need to make function calls from the template anyway.

Whatever you are doing with the function you could do with a pipe instead:

pipe function

The pipe accepts a value as an input (and optionally additional arguments) and whatever the transform method returns is what will be displayed in the template.

pipeOne

It is the same basic idea as calling a function just… better. But why is it better?

The main benefit of a pipe is that they are pure by default. This means that for the same inputs the pipe should always generate the same output and not trigger any side effects.

What this means is that when change detection is run, the transform method only needs to be re-evaluated if the input to the pipe changes.

To demonstrate this, I created two template functions and two pipes in a StackBlitz. You can trigger change detection by clicking the button in the template.

The first time the component renders, all of the template functions and pipes will be evaluated which we can see by the messages they log out to the console:

template functions and pipes being evaluated

But, every time we trigger change detection after that, only the template functions are re-evaluated:

only the template functions are re-evaluated

For this reason, it’s a good idea to use pipes by default.

Learn to build modern Angular apps with my course