🅰️ Angular Q11 / 125

What are pipes in Angular? Can you create custom pipes?

AI-Powered Answer ✓ Answered

Pipes are a powerful feature in Angular used to transform data before it is displayed in the view. They enhance data presentation by allowing data manipulation directly within templates.

Pipes are simple functions used in Angular templates to transform data. They take data as input and return transformed data, making it easy to format, filter, or sort information directly within your HTML without altering the component's underlying data.

Angular comes with several built-in pipes like DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. For example, the DatePipe can format a JavaScript Date object into various human-readable formats.

html
<p>Original date: {{ myDate }}</p>
<p>Formatted date: {{ myDate | date:'shortDate' }}</p>
<p>Currency: {{ price | currency:'USD':'symbol':'1.2-2' }}</p>

Creating Custom Pipes

Yes, Angular allows you to create custom pipes to encapsulate any data transformation logic that isn't covered by the built-in pipes or to reuse complex transformations across your application. This promotes reusability and keeps your component logic clean.

  • Generate a pipe using the Angular CLI: ng generate pipe <pipe-name>.
  • Implement the PipeTransform interface and its transform method. The transform method takes the input value and optional arguments, returning the transformed value.
  • Decorate the class with @Pipe decorator, providing a unique name property for the pipe.
  • Declare the custom pipe in an Angular module (typically app.module.ts) or a standalone component/pipe.

Example: Custom Reverse String Pipe

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

@Pipe({
  name: 'reverseString',
  standalone: true // Or declare in a module
})
export class ReverseStringPipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return '';
    return value.split('').reverse().join('');
  }
}

To use this pipe in a template, you would simply apply it like any other pipe: <p>{{ 'Hello Angular' | reverseString }}</p> which would output 'ralugnA olleH'.