Angular: Create custom pipe in Angular

Angular provides built-in pipes for typical data transformations, including transformations for internationalization (i18n), which use locale information to format data. The following are commonly used built-in pipes for data formatting:

  • DatePipe: Formats a date value according to locale rules.
  • UpperCasePipe: Transforms text to all upper case.
  • LowerCasePipe: Transforms text to all lower case.
  • CurrencyPipe: Transforms a number to a currency string, formatted according to locale rules.
  • DecimalPipe: Transforms a number into a string with a decimal point, formatted according to locale rules.
  • PercentPipe: Transforms a number to a percentage string, formatted according to locale rules.

Also Read: Angular: All about pipes template in angular

Creating pipes for custom data transformations:

Create custom pipes to encapsulate transformations that are not provided with the built-in pipes. You can then use your custom pipe in template expressions, the same way you use built-in pipes—to transform input values to output values for display.

We can create custom pipes in Angular in two ways.

  1. Using ng generate pipe angular CLI command.
  2. Manually.

Marking a class as a pipe:

To make any class Pipe, apply the @Pipe decorator to the class. Use UpperCamelCase (the general convention for class names) for the pipe class name. Now you need to Implement the PipeTransform interface in your custom pipe class to perform the transformation.

Include your pipe in the declarations field of the NgModule metadata in order for it to be available to a template. 

Using the PipeTransform interface:

Implement the PipeTransform interface in your custom pipe class to perform the transformation.

Angular invokes the transform method with the value of a binding as the first argument, and any parameters as the second argument in list form, and returns the transformed value.

// exponential-strength.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'}) // name -> to use this pipe
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent?: number): number {
    return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  }
}
// power-booster.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-power-booster',
  template: `
    <h2>Power Booster</h2>
    <p>Super power boost: {{2 | exponentialStrength: 10}}</p>
  `
})
export class PowerBoosterComponent { }

Whenever we create a custom pipe, by default they are pure pipe. But sometimes we need an Impure pipe that can trigger whenever any change in the value of the reference object. Like adding new value to the array.

In the same way, as we created pure pipe we can create impure pipe also. The only difference is we need to pass pure:false.

Caching HTTP requests:

Let create a pipe that calls the server only when the requested URL changes, as shown in the following example, and use the pipe to cache the server response.

// fetch-json.pipe.ts
import { HttpClient } from '@angular/common/http';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'fetch',
  pure: false
})
export class FetchJsonPipe implements PipeTransform {
  private cachedData: any = null;
  private cachedUrl = '';

  constructor(private http: HttpClient) { }

  transform(url: string): any {
    if (url !== this.cachedUrl) {
      this.cachedData = null;
      this.cachedUrl = url;
      this.http.get(url).subscribe(result => this.cachedData = result);
    }

    return this.cachedData;
  }
}
import { Component } from '@angular/core';

@Component({
  selector: 'app-ip-config',
  template: `
    <h2>Heroes from JSON File</h2>

    <div *ngFor="let i of [1,2,3,4]">
     <p>Heroes as JSON:
      {{'http://ip-api.com/json/24.48.0.'+i | fetch | json}}
    </p>
</div>`
})
export class IpConfigComponent { }

In the above example, a breakpoint on the pipe’s request for data shows the following:

  • Each binding gets its own pipe instance.
  • Each pipe instance caches its own URL and data and calls the server only once.

Also Read: Angular: All about pipes template in angular

Checkout Code : https://github.com/Singhak/AngularConcepts

References :
Transforming Data Using Pipes

FAQ

Can we create custom pipe in angular?

Yes, We can create custom pipe in angular via implementing PipeTransform interface

How many types of angular pipe?

There are two type of angular type: 1. Pure pipe 2. Impure pipe

How we can create custom pipe?

1. Using ng generate pipe Angular CLI command.
2. Manually.

Leave a Reply