Angular — Utilizing custom pure pipe to improve performance

Liu Ting Chun
4 min readNov 12, 2020

Pipe is a powerful feature in Angular to achieve data transformation in templates.

@Pipe({name: 'trim'})
export class TrimPipe implements PipeTransform {
transform(value: string): string {
return value.trim();
}
}
@Component({
template: `{{ value | trim }}`,
...
})
export class AppComponent {...}

However, not many Angular developers like working with custom pipe due to the fact that it is more heavy weighted than a static Util class, with more codes to write, classes to maintain and restrictions for usage. The same functionality implemented with a static method is usually cleaner than the one wrapped in a custom pipe.

export class Util {
static trim(value: string): string {
return value.trim();
}
}
@Component({
template: `{{ Util.trim(value) }}`,
...
})
export class AppComponent {...}

In fact, the major benefit of using pure custom pipe is not about the functionality, but the performance. Here I am going to explain with an example.

Image from SAP

“Memoization”

The major benefit of custom pipe is that it can “anchor” to the change detection of its input value. Using the TrimPipe above as an example, when we put this in our template:

--

--

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.