Benefits Of Using Pipe Over Function In Angular
Tags: angular, webdev, angularpipe, stackblogger
Published: 2021-10-31 09:24:13

The article is originally published at my blog here: [Benefits Of Using Pipe Over Function In Angular](https://stackblogger.com/benefits-of-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](https://angular.io/api?type=pipe).*

## 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`

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

`app.component.html`

```html
<b>Date Pipe Example: </b>
<span>{{ date | date: 'shortDate'}}</span>
```

**Result with `Date Pipe`**

![Output Date after using Date Pipe](https://stackblogger.com/wp-content/uploads/2021/10/angular-date-pipe-output-min.png)

**Result without `Date Pipe`**

![Output Date without using Date Pipe](https://stackblogger.com/wp-content/uploads/2021/10/angular-date-output-without-date-pipe-min.png)

## 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).

```typescript
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.

```typescript
@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](https://fakestoreapi.com/products) to demonstrate it better.

### 1. Create a data table with fake api response

`app.component.ts`

```typescript
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`

```html
<table>
  <tr>
    <th>Title</th>
    <th>Category</th>
    <th>Description</th>
  </tr>
  <tr *ngFor="let item of data">
    <td>{{item.title}}</td>
    <td>{{item.category}}</td>
    <td>{{item.description}}</td>
  </tr>
</table>
```

### 2. Create a custom pipe `custom-upper`
```
ng g p custom-upper
```

![Custom Pipe output](https://stackblogger.com/wp-content/uploads/2021/10/create-custom-pipe-in-angular-min.png)

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

```typescript
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();
  }
}
```

### 3. Consume the custom pipe in template

Call the `customUpper` in the template code.

```html
<td>{{item.category | customUpper}}</td>
```

### 4. Check the output

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

![Uppercase using angular pipe](https://stackblogger.com/wp-content/uploads/2021/10/uppercase-with-angular-pure-pipe.gif)

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 which is fine. 

Now check the same example without using a pure pipe.

## 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.

### 1. 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.

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

### 2. Consume the custom uppercase method in template

Call the method from template.

```html
<td>{{convertToUpperCase(item.category)}}</td>
```

Check the output.

![Uppercase in Angular using a method at component](https://stackblogger.com/wp-content/uploads/2021/10/uppercase-in-angular-using-a-method.gif)

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.

The article is originally published at my blog here: [Benefits Of Using Pipe Over Function In Angular](https://stackblogger.com/benefits-of-pipe-over-function-in-angular/)

## 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](https://stackblogger.com/5-best-ways-to-optimize-angular-for-scaling/)

Must Read Articles:
* [5 Best Google Charts to Use in Angular (2021)](https://stackblogger.com/5-best-google-charts-for-angular/)
* [Angular Material 12 Table, Sorting, Searching & Pagination](https://stackblogger.com/angular-material-data-table-tutorial/)
* [RxJS forkJoin: Definition and Real World Uses](https://stackblogger.com/rxjs-forkjoin-definition-and-real-world-uses/)
* [5 Great SEO Ideas To Improve Angular Website Ranking](https://stackblogger.com/5-great-seo-ideas-to-improve-angular-website-ranking/)
* [Real World Examples of 5 Common Observable Operators](https://stackblogger.com/real-world-examples-of-some-common-observable-operators/)