[Case Study] Benefits Of Using Pipe Over Function In Angular

Do you use functions / methods to implement various conditions and DOM manipulations in Angular ? If yes, trust me it will worsen your website performance. In this tutorial I will explain how pipes increase your angular website performance and what are the various benefits of using Pipe over Functions based on a case study.

Before diving straight into tutorial, let’s start with some basic questions.

Angular Pipe

The first question comes in mind- What is Pipe? A simple definition of pipe- it is a decorative function in Angular used to manipulate DOM. It takes an untransformed value as input and returns a transformed value as output.

Types of Pipe

Various built-in pipes are provided by Angular- AsyncPipe, CurrencyPipe, DatePipe, JsonPipe and many more. Complete list here.

How to use pipe in code?

This could be a common question for beginners- how can I use a pipe? Check the code below.

The example code below demonstrates the use of date pipe. See how the output is manipulated on the DOM.

app.component.ts


date: Date;

constructor() {
  this.date = new Date();
}

app.component.html


Date Pipe Example: 
{{ date | date: 'shortDate'}}

Result with Date Pipe

Output Date after using Date Pipe
Output Date after using Date Pipe

Result without Date Pipe

Output Date without using Date Pipe
Output Date without using Date Pipe

Pure and Impure Pipe

Pure pipe is a type of function which runs only when a change has been done in the input value. They are called as pure because they do not run every time a state is changed or a change detection happened. They are only called when a value is changed. This improves the performance (see below case study).


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customUpper'
})
export class CustomUpperPipe implements PipeTransform {

  transform(value: string): string {
    console.log('Custom pipe is called');
    return value.toUpperCase();
  }
}

Impure pipe is a type of function which runs for every Angular lifecycle events as well as whenever state or input value changes.


@Pipe({
  name: 'customUpper',
  pure: false  // <--- this will convert a pure pipe to impure one
})

It is not advisable to use a method to manipulate your DOM. Use pipes instead of methods if you have a big application and want to improve performance.

Benefits of using Pipe over Function

Let's take an example of doing same thing once with method and once with pipe.

Uppercase using pipe

In this case study we will take an example of converting string to uppercase using a pure pipe. And we will see the output.

Create a server side data table with fake JSON api to demonstrate it better.

Create a data table with fake api response

app.component.ts


import { HttpClient } from '@angular/common/http';
import { Component, Injectable, OnInit } from '@angular/core';

@Injectable()
export class AppService {
  constructor(private http: HttpClient) { }

  public getData() {
    return this.http.get('https://fakestoreapi.com/products');
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [AppService]
})
export class AppComponent implements OnInit {
  date: Date;
  data: any = [];

  constructor(private appService: AppService) {
    this.date = new Date();
  }

  ngOnInit() {
    this.appService.getData().subscribe(data => {
      this.data = data;
    });
  }
}

app.component.html


Title Category Description
{{item.title}} {{item.category}} {{item.description}}

Create a custom pipe custom-upper


ng g p custom-upper
Custom Pipe output
Custom Pipe output

Put the code to convert string to uppercase in the created pipe.


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customUpper'
})
export class CustomUpperPipe implements PipeTransform {

  transform(value: string): string {
    console.log('Custom pipe is called');  // console.log will let us know how many times it's called
    return value.toUpperCase();
  }
}

Consume the custom pipe in template

Call the customUpper in the template code.


{{item.category | customUpper}}

Check the output

Run the app and open Browser Console to check the output.

Uppercase using angular pipe
Uppercase using angular pipe

Notice in the screen above that the console is printed 20 times. Its because the api gives 20 results and it ran once for each row.

Uppercase using method

In the above case study we already seen the output of converting string to uppercase using a pipe. In this case study we will take the sample example ie. convert string to uppercase but using a method at component. And we will see the output.

Convert to uppercase using a method

Create a method convertToUpperCase in component to convert text to upper case. Put a console.log in the function to know how many times it is called from UI.


convertToUpperCase(str: string) {
    console.log('Uppercase fn is called');  // put a console to know how many times the function is called
    return str.toUpperCase();
}

Consume the custom uppercase method in template

Call the method from template.


{{convertToUpperCase(item.category)}}

Check the output.

Uppercase in Angular using a method at component
Uppercase in Angular using a method at component

Notice the output in console. You will see it's called 4 times more than what was called in pipe. This will make a huge difference if you are building a large Angular application that has complex layouts and binding.

Conclusion

In this article we learnt about the benefits of using Pipe over Function in Angular. They make a huge difference in the performance.

Check this article to optimize your Angular application: 5 Best Ways To Optimize Angular For Scaling

Must Read Articles:

Leave a Reply

Your email address will not be published. Required fields are marked *