Creating Custom Pipes in Angular

While writing angular applications, pipes are the powerful way to transform your data into your template. Angular provides many built in pipes like date, uppercase, currency. If you are writing complex angular, you may need your custom way of data transformation. And That is were custom pipes come in.

In this blog, we will see what pipes are, why and when to create a pipe and how to build both pure and impure custom pipes in Angular with practical examples.


What is Pipe in Angular ?

Pipe is a simple function that:

  1. Takes an Input
  2. Transforms it
  3. Returns a formatted output.

Pipes are directly used in template/HTML using the “|” symbol:

<p>{{ username | uppercase }}</p>

In above code sample, what ever username you provide will be transformed to the uppercase.

This is the example of built in pipe. But what if you want to have your custom tarnsformation logic, that needed to be used in multiple HTML/Template ?

Custom Pipe is the answer to above question.


How to create a custom Pipe ?

Step: 1 – Genereata a pipe using angular cli

ng generate pipe capitalize

This will generate the capitalize.pipe.ts and also register the pipe in angular module.

Step: 2 – Write a transofrmation logic in your pipe file

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

@Pipe({
  name: 'capitalize'
})

export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return '';
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}

Step: 3 – Consume the Pipe in your HTML

<div>{{ 'hardik' | capitalize }}</div>

Note: Make sure you import capitalize pipe in your component.ts file.


How to use multiple parameters ?

Sometimes your pipe’s transformation logic requires multiple parameters to be passed. To achieve that, your code looks like this:

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

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {

  transform(value: unknown, length: number = 10, replacement: string = '...'): unknown {
    if (!value) return value;
    const str = String(value);
    if (str.length <= length) return str;
    return str.substring(0, length) + replacement;
  }
}

and your HTML Template:

{{ description | truncate:50:'...' }}

Home » Creating Custom Pipes in Angular

Leave a Comment