Angular Pipes

Angular pipes are a useful feature that allows you to transform the data that is being displayed in your application. Pipes can be used to format, filter, and transform data in a variety of ways. In this article, we will explain what pipes are, how they work, and provide examples of how you can use them in your Angular applications.

 

What are Pipes?

Pipes in Angular are a way to transform data before it is displayed in the view. Pipes can be used to format, filter, and transform data in a variety of ways. Pipes are easy to use and can be added to your templates with ease.

Angular comes with a number of built-in pipes that you can use out of the box, but you can also create your own custom pipes to fit your specific needs.

 

How do Pipes work?

Pipes in Angular work by taking a value and transforming it in some way before it is displayed in the view. Pipes are essentially a function that takes an input and returns an output. The input to the pipe can be any data type, and the output can be any data type as well.

To use a pipe in your Angular application, you simply need to add it to the template where the data is being displayed. Pipes are added to the template using the pipe symbol (|), followed by the name of the pipe.

For example, if you want to format a date in your Angular application, you can use the built-in date pipe as follows:

{{ myDate | date:'shortDate' }}

In this example, myDate is the input value and shortDate is the argument that is passed to the date pipe. The date pipe will then format the date according to the specified format and display it in the view.

 

Types of Pipes

There are two types of pipes in Angular: pure and impure. Pure pipes are pipes that only transform data when the input value changes. Impure pipes, on the other hand, may transform data even if the input value has not changed.

Built-in Pipes Angular comes with a number of built-in pipes that you can use out of the box. These pipes are designed to handle common tasks such as formatting dates, converting text to uppercase or lowercase, and filtering arrays.

Here are some examples of the most commonly used built-in pipes:

 

DatePipe

This pipe is used to format dates in different ways. It accepts an optional format string that can be used to format the date according to a particular pattern. For example:

{{ today | date:'dd/MM/yyyy' }}

 

DecimalPipe

This pipe is used to format numbers with decimal places. It accepts an optional argument for the number of digits to show after the decimal point. For example:

{{ price | number:'1.2-2' }}

 

CurrencyPipe

This pipe is used to format currency values. It accepts an optional argument for the currency symbol, currency code, and display format. For example:

{{ price | currency:'USD':'symbol':'1.2-2' }}

 

PercentPipe

This pipe is used to format numbers as percentages. It accepts an optional argument for the number of digits to show after the decimal point. For example:

{{ discount | percent:'1.2-2' }}

 

SlicePipe

This pipe is used to extract a portion of a string or array. It accepts two arguments: the start index and the end index. For example:

{{ text | slice:0:10 }}

 

LowerCasePipe

This pipe is used to convert text to lowercase. For example:

{{ text | lowercase }}

 

UpperCasePipe

This pipe is used to convert text to uppercase. For example:

{{ text | uppercase }}

 

TitleCasePipe

This pipe is used to convert text to title case. For example:

{{ text | titlecase }}

 

AsyncPipe

This pipe is used to subscribe to and display the latest value of an asynchronous data source. For example:

{{ data$ | async }}

 

KeyValuePipe

This pipe is used to iterate over an object and return its key-value pairs as an array. For example:

<div *ngFor="let item of myObj | keyvalue"> 
    {{ item.key }}: {{ item.value }} 
</div>

 

JsonPipe

This pipe is used to stringify an object into JSON format. For example:

{{ myObj | json }}

These are the various built-in pipes in Angular that can be used to transform and format data in templates.

 

 

Custom Pipes

Custom pipes in Angular allow you to transform data according to your specific needs. You can create your own pipe by implementing the PipeTransform interface and defining the transform() method to return the modified data.

Here's a simple example of creating a custom pipe that formats a string to title case:

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

@Pipe({name: 'titlecase'})
export class TitleCasePipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return value;
    return value.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  }
}

In the code above, we have created a pipe called titlecase. This pipe takes a string as input, and transforms it to title case using the transform() method. The transform() method uses a combination of toLowerCase(), split(), map(), charAt(), toUpperCase(), slice(), and join() methods to format the string to title case.

Once we have defined our custom pipe, we can use it in our component templates like any other pipe:

<h1>{{ 'hello world' | titlecase }}</h1>

This will output Hello World.

Another popular use case for custom pipes is to format dates in a more human-readable format. Here's an example of a custom pipe that shows how long ago a date was:

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

@Pipe({name: 'timeAgo'})
export class TimeAgoPipe implements PipeTransform {
  transform(value: string, format?: string): string {
    if (!value) return value;
    const date = moment(value, format);
    return date.isValid() ? date.fromNow() : value;
  }
}

In this example, we have used the popular moment.js library to format the date. The transform() method takes two parameters: the date string, and an optional format string. The moment() function parses the date string using the format string, if provided. If the date is valid, the fromNow() method returns a string that represents how long ago the date was (e.g. "2 days ago", "a month ago", etc.). If the date is invalid, the original value is returned.

To use this custom pipe in our component templates, we can pass in a date string like this:

<p>{{ '2022-02-08T08:14:35.000Z' | timeAgo }}</p>

This will output something like "3 days ago" (depending on the current date).

In conclusion, custom pipes in Angular are a powerful way to transform data according to your specific needs. By implementing the PipeTransform interface, you can create pipes that can format strings, numbers, dates, and more in a variety of ways.