Angular Pipes

In this article we will learn about what angular pipes is and what angular pipes uses are
What is Angular pipes are and their purpose?
Pipes are a special operator in Angular template expressions that allows you to transform data declaratively in your template. Pipes let you declare a transformation function once and then use that transformation across multiple templates. Angular pipes use the vertical bar character( | ), inspired by the Unix pipe.
Angular Pipes allows its users to change the format in which data is being displayed on the screen. For instance, consider the date format. Dates can be represented in multiple ways, and the user can decide which one to use with the help of Angular Pipes.
Overall, pipes are a powerful feature in Angular that allow you to transform data in templates without requiring additional code in the component. By using built-in pipes or creating custom pipes, you can format dates , numbers , and strings , filter data , and perform other useful transformations.
Types of Angular Pipes
Angular provides built-in pipes for typical data transformations, including transformations for internationalization (i18n), which use locale information to format data. The following are commonly used built-in pipes for data formatting:
DatePipe: Formats a date value according to locale rules.UpperCasePipe: Transforms text to all upper case.LowerCasePipe: Transforms text to all lower case.CurrencyPipe: Transforms a number to a currency string, formatted according to locale rules.DecimalPipe: Transforms a number into a string with a decimal point, formatted according to locale rules.PercentPipe: Transforms a number to a percentage string, formatted according to locale rules.AsyncPipe: Subscribe and unsubscribe to an asynchronous source such as an observable.JsonPipe: Display a component object property to the screen as JSON for debugging.
Angular makes provision to create custom pipes that convert the data in the format that you desire. Angular Pipes are TypeScript classes with the @Pipe decorator. The decorator has a name property in its metadata that specifies the Pipe and how and where it is used.
Here are the general steps to create a custom pipe:
Create a TypeScript Class with an export keyword.
Decorate it with the @Pipe decorator and pass the name property to it.
Implement the pipe transform interface in the class.
Implement the transform method imposed due to the interface.
Return the transformed data with the pipe.
Add this pipe class to the declarations array of the module where you want to use it.
Use Cases of Angular Pipes
Some practical use cases for using pipes in Angular applications are Data Masking, Unit Conversion ,Filtering Data, Sorting Data and Custom Transformations on Data
This are the examples where pipes are used for dynamic data transformation in a user-friendly format
Date Formatting - Angular's
DatePipecan format a date object or timestamp into various human-readable formats.Currency Formatting - The
CurrencyPipeis used to format numbers into currency format dynamically.Uppercase/Lowercase Transformation - You can use the
UpperCasePipeorLowerCasePipeto transform text dynamically.Decimal Formatting - The
DecimalPipeallows you to format numbers with specific precision.Async Pipe (Handling Observable Data) - The
AsyncPipeis a powerful tool when dealing with asynchronous data, such as from an API or aPromise.
Angular Pipes Code Snippets Example
- AsyncPipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x: Promise<string> | null = Promise.resolve("hello world");
}
<!-- For app.component.html -->
<p>{{x | async}}</p>
- CurrencyPipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x = 100;
}
<!--For app.component.html-->
<p>{{x | currency:'CAD':'symbol':'4.2-3':'en'}}</p>
- DatePipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x = new Date(2023, 1, 3, 1, 1, 1);
}
<!-- For app.component.html -->
<p>{{x | date: 'YYYY-MM-dd h:mm:ss a'}}</p>
- DecimalPipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x = 100.88;
}
<!-- For app.component.html -->
<p>{{x | number: '1.0-1'}}</p>
- JsonPipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x: { [k: string]: number } = {
foo: 1,
bar: 2,
baz: 3
};
}
<!-- For app.component.html -->
<p>{{ x | json }}</p>
- LowerCasePipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x: string = "The quick brown fox jumps over the lazy dog ";
}
<!-- For app.component.html -->
<p>{{x | lowercase}}</p>
- PercentPipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x = 0.88888;
}
<!-- For app.component.html -->
<p>{{x | percent: '1.0-1': 'en'}}</p>
- UpperCasePipe:
// For app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
x: string = "The quick brown fox jumps over the lazy dog ";
}
<!-- For app.component.html -->
<p>{{x | uppercase}}</p>
Example on creating custom pipes in Angular using ng generate Angular CLI command
Step 1
First, open your command prompt.
Step 2
Navigate to your Angular project directory where you want to create pipe
Step 3
Use the following command to generate a custom pipe
ng generate pipe pipe-name
From the above command, you can replace a pipe name with your own name.
For example:
ng generate pipe capitalize
This command will generate a new pipe file named capitalize.pipe.ts in the src/app directory, along with a corresponding test file.
Your custom pipe will look something like this in capitalize.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
if (typeof value !== 'string') {
return value;
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
Step 4
Let's add Pipe transform logic into the transform method. here is an example of a pipe that takes input as milliseconds and returns output in seconds.
How to Use Custom Pipes
You can now use your custom pipe capitalize in your Angular templates by adding it to the declarations array of the module where you want to use it.
For example, if you want to use it in the app.module.ts file, add it like this:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CapitalizePipe } from './capitalize.pipe'; // Import the pipe
@NgModule({
declarations: [
AppComponent,
CapitalizePipe // Add the pipe to declarations
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Once a custom pipe is created and registered, you can use it directly in Angular templates using the pipe operator (|). You can chain multiple pipes together to apply multiple transformations sequentially. Now you can use only the names of capitalize pipe in your templates like this:
<p>{{ 'hello world' | capitalize }}</p>
This will output Hello world.
References
https://angular.dev/guide/templates/pipes
https://www.simplilearn.com/tutorials/angular-tutorial/angular-pipes#:~:text=Angular%20Pipes%20allows%20its%20users,the%20help%20of%20Angular%20Pipes.
https://medium.com/@aqeelabbas3972/pipes-in-angular-6a871589299d#:~:text=Overall%2C%20pipes%20are%20a%20powerful,and%20perform%20other%20useful%20transformations.
https://v17.angular.io/guide/pipes-overview
https://medium.com/@krishsurya1249/angular-pipes-45923a4e1891
https://www.telerik.com/blogs/angular-basics-built-pipes-examples-each
https://www.angularminds.com/blog/creating-custom-pipe-in-angular-a-step-by-step-tutorial


