0
0
Angularframework~5 mins

Creating custom pipes in Angular

Choose your learning style9 modes available
Introduction

Custom pipes help you change how data looks in your app. They make your templates cleaner and your code easier to read.

You want to format dates in a special way not covered by built-in pipes.
You need to shorten long text with an ellipsis.
You want to convert text to uppercase but only for certain words.
You want to filter or transform a list before showing it.
You want to create reusable formatting logic for numbers or strings.
Syntax
Angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'pipeName'
})
export class PipeNamePipe implements PipeTransform {
  transform(value: any, ...args: any[]): any {
    // your transformation logic here
    return transformedValue;
  }
}

The @Pipe decorator defines the pipe's name used in templates.

The transform method takes the input value and optional arguments, then returns the transformed output.

Examples
This pipe adds an exclamation mark to any string.
Angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'exclaim' })
export class ExclaimPipe implements PipeTransform {
  transform(value: string): string {
    return value + '!';
  }
}
This pipe shortens text to a given length and adds '...' if it was cut.
Angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit: number): string {
    return value.length > limit ? value.substring(0, limit) + '...' : value;
  }
}
Sample Program

This example shows a custom pipe named reverse that flips a string backwards. The component uses it to show the original and reversed text.

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

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ReversePipe],
  template: `<h1>Original: {{ text }}</h1><h2>Reversed: {{ text | reverse }}</h2>`
})
export class AppComponent {
  text = 'hello';
}
OutputSuccess
Important Notes

Always name your pipes with lowercase letters and no spaces for easy use in templates.

Custom pipes should be pure by default, meaning they only change output when input changes, for better performance.

Remember to add your pipe to the module or use standalone components to make it available.

Summary

Custom pipes let you change how data looks in your Angular templates.

They use a transform method to convert input to output.

Use them to keep your templates clean and reuse formatting logic.