Introduction

Pipes | can be used in Angular in order to transform different types of string data such as dates and currency in a specific format to display to the user. Pipes are used in the templates. They take in a value and return that same value transformed. Pipes are declared once and can be reused anywhere you want in your application.

There are built-in pipes that are used very often in Angular. They are:

PercentPipe: Takes a number and changes it into a percentage of type string. Locale rules are adhered to.

CurrencyPipe: Takes a number and changes it into a currency of type string. Locale rules are adhered to.

DecimalPipe: Takes a number and changes it into a decimal of type string. Locale rules are adhered to.

DatePipe: Takes a date and formats it. Locale rules are adhered to.

LowerCasePipe: Takes a string and changes it to lowercase.

UpperCasePipe: Takes a string and changes it to uppercase.

Examples

Formatting dates

Here are some examples using pipes in order to change and display dates to the user in a certain manner.

//app.component.ts
export class AppComponent {
  public currentDate: Date = new Date();
}
<!-- app.component.html -->
<!-- Thu Mar 04 2021 23:40:45 GMT-0500 (Eastern Standard Time) -->
<p>{{currentDate}}</p>

<!-- Mar 4, 2021 -->
<p>{{currentDate | date}}</p>

We can format the date in a specific manner:

<!-- app.component.html -->
<!-- Mar 4, 2021 -->
<p>{{currentDate | date}}</p>

<!-- 2021-03-04 -->
<p>{{currentDate | date: "yyyy-MM-dd"}}</p>

We can use chaining to format the date in a specific format:

<!-- app.component.html -->
<!-- MAR 4, 2021 -->
<p>{{currentDate | date | uppercase}}</p>

Creating a custom pipe

A Custom pipe can be created using Angular CLI:

ng g pipe namOfPipe

Example of a custom pipe class

We will create a custom pipe class that will return a person’s full name:

“Custom Pipes”

We can then leverage this custom pipe in any template in our application like so:

{{user | fullName}}