Why use “pipe” instead of “function” in Angular?

Mushegh Zakaryan
3 min readAug 17, 2022

Hello, in this short article I will show you how pipe can improve your application performance.

Use pipes to change strings, monetary values, dates, and other data so that it may be displayed. Pipes are straightforward functions that can take an input value and return a changed value in template expressions. Because you only need to declare each pipe once, pipes are advantageous because you may utilize them throughout your program. Instead of using the raw string format to display a date, for instance, you would use a pipe to display April 15, 1988.
By using Pipe, you’ll see an overall improvement in performance.

Imagine you have very simple code where you need to show a tooltip, but you need to modify data and then show it.

value

In this image you can see a value object, we need to modify this and use only a name like in the image below.

1. Let's do it using function and check how this will work.

(html)<span[matTooltip]=”tooltip(value)”></span>(.component.ts)pluck(arr, key): [] {
return arr.map(i => i[key]);
}

tooltip(value): string {
console.log('something');
return this.pluck(value, 'name').join(', ');
}

We just received the name in the tooltip function, merge it with a comma, and then return the new string.
Now let's see how many times Angular calls the ‘tooltip’ function.

2. Let’s do the same login using pipe

let’s create pipe:

import {Pipe, PipeTransform} from '@angular/core';@Pipe({name: ‘tooltip’})export class TooltipPipe implements PipeTransform {
/**
* Transform
*
* @param value
* @param {string[]} args
* @returns {any}
*/
transform(value: any, args: string[]): any {
console.log(‘using pipe’);
return this.pluck(value, ‘name’).join(‘, ‘);
}
pluck(arr, key): [] {
return arr.map(i => i[key]);
}
}
<span[matTooltip]=”value | tooltip: value”></span>

Now you are ready to see ‘pipe magic’.

Pipes are by default specified as pure, allowing Angular to only run the pipe when it notices a pure change to the input value. A change to a basic input value (such as a String, Number, Boolean, or Symbol) or an altered object reference are both considered pure changes (such as Date, Array, Function, or Object).

Do not use functions where you can use pipe.

I hope this brief article may assist you in improving the performance of your application.

For more information: https://angular.io/guide/pipes

Best Regards,
Mushegh Zakaryan

--

--