How to Create Custom Pipe in Angular 16 Application
Angular 16 Pipe tutorial; In this tutorial, we are going to learn about Angular default and custom pipes.
Angular offers tons of built-in Pipes, that helps you deal with various types of programming problems while developing single page web application.
We will also learn to create custom Angular Pipe from scratch. Without further ado let’s get started:
Angular Custom Pipe Example
- Working with Angular Pipes
- Angular Built-in Pipes
- Creating Custom Pipe in Angular
Getting Started
We are going to discuss Pipes in Angular, Pipes are very useful when it comes to managing data within interpolation “{{ | }}”. In Angular1, pipes were referred to as filters now they are famous by the name of Pipes.
In order to transform data, we use the character |. Check out the syntax for the same below.
{{ i will become uppercase one day | uppercase }}
Pipes accept date, arrays, strings, and integers as inputs. Inputs are separated with |. Later, the inputs will be converted in the desired format before displaying them in the browser.
We are going look at a few examples involving pipes.
In the given example, we are trying to display the given text in uppercase. You will be able to get it done using pipes as shown below –
We have defined the convertText variable in the app.component.ts file –
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
convertText: string = "I Am Being Managed By Pipes";
}
You will find the following code segment in the app.component.html
file.
app.component.html
<div style="text-align:center">
<img width="230" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
<div style="padding-top: 30px">
{{convertText | lowercase}}
</div>
<div style="padding-top: 30px">
{{convertText | uppercase}}
</div>
</div>
You will find a screenshot of the browser below –
Angular Built-in Pipes
Angular Pipes help you to reconstruct data instantly in your angular app.
Angular offers some built-in Pipes API to update your data in a quick snap.
It also allows you to create custom Pipes in your app. Let’s find out some of the very useful Angular Pipes given below.
Built-in Angular Pipes
Async Pipe
Currency Pipe
Date Pipe
Slice Pipe
Decimal Pipe
Json Pipe
Percent Pipe
LowerCase Pipe
UpperCase Pipe
How to Use Built-in Pipes in Angular 12
Let’s find out how we can use built-in Angular pipes.
Async Pipe
The Async pipe is considered the best practice when you are getting data in the form of observables.
The async pipe subscribes to an Observable/Promise automatically and returns the transmitted values.
<ul>
<li *ngFor="let users of Users | async">
{{ users.name }}
</li>
</ul>
Currency Pipe
The currency pipe in angular helps to convert numbers in various currencies.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style="text-align:center">
<h3> Currency Pipe</h3>
<p>{{ itemPrice | currency:'USD':true }}</p>
<p>{{ itemPrice | currency:'EUR':true}}</p>
<p>{{ itemPrice | currency:'INR' }}</p>
</div>
`
})
export class AppComponent {
itemPrice: number = 5.50;
}
Date Pipe
The date pipe in Angular helps to format the Date in Angular.
To know more about DatePipe operator check out: Angular Date Pipe Tutorial with Date Format Examples.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style="text-align:center">
<h3>Date Pipe</h3>
<p>{{ currentDate | date:'fullDate' }}<p>
<p>{{ numDateFormat | date:'medium' }}<p>
<p>{{ getYear | date:'yy' }}<p>
<p>{{ getTime | date:'Hm' }}<p>
</div>
`
})
export class AppComponent {
currentDate = Date.now();
numDateFormat = 1478496544151;
getYear = 'Tue Dec 12 2018 11:20:18 GMT+0530';
getTime = 'Wed Jan 20 2019 12:20:18 GMT+0530';
}
Slice Pipe
The Slice pipe API in Angular formulate a subset list or string.
<ul>
<li *ngFor="let users of Users | slice:2">
{{ users }}
</li>
</ul>
Decimal Pipe
The Decimal pipe helps to format decimal values in Angular. Decimal Pipe API concerns with CommonModule in Angular.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style="text-align:center">
<h3>Decimal Pipe</h3>
<p> {{myNum1 | number}} </p>
<p> {{myNum2 | number}} </p>
</div>
`
})
export class AppComponent {
myNum1: number = 7.4364646;
myNum2: number = 0.9;
}
Json Pipe
The JSON pipe API works to expose an object as a JSON string in the Angular app. It complements the JSON.stringify method behind the curtains.
{{ objectName | json }}
Percent Pipe
The Percent pipe API in Angular modifies a number into its percentage value.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style="text-align:center">
<h3>LowerCase & UpperCase Pipe</h3>
<!--output '35%'-->
<p>A: {{numA | percent}}</p>
<!--output '0,245.950%'-->
<p>B: {{numB | percent:'4.3-5'}}</p>
</div>
`
})
export class AppComponent {
numA: number = 0.349;
numB: number = 2.4595;
}
LowerCase & UpperCase Pipe
Lowercase or Uppercase pipes help to format text to either lower or upper case in an Angular app.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style="text-align:center">
<h3>LowerCase & UpperCase Pipe</h3>
<p> {{convertText | lowercase}} </p>
<p> {{convertText | uppercase}} </p>
</div>
`
})
export class AppComponent {
convertText: string = "I Am Being Managed By Pipes";
}
How to Create Custom Pipe in Angular 12
Now, let’s see how we can create a custom pipe. In order to create a custom pipe to count words, run a given below command in Angular CLI:
ng g pipe wordcount
That’s how it will look after running the command in Angular CLI.
ng g pipe wordcount
# CREATE src/app/wordcount.pipe.spec.ts (199 bytes)
# CREATE src/app/wordcount.pipe.ts (207 bytes)
# UPDATE src/app/app.module.ts (433 bytes)
This command will generate wordcount.pipe.ts
and wordcount.pipe.spec.ts
files and update app.module.ts
file automatically.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// Custom Pipe imported here by Angular CLI
import { WordcountPipe } from './wordcount.pipe';
@NgModule({
declarations: [
AppComponent,
WordcountPipe // Wordcount pipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now let’s write a logic for word counter in a string in Angular using PIPE API service.
Open the wordcount.pipe.ts
file and use the given below code.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'wordcount'
})
export class WordcountPipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.trim().split(/\s+/).length;
}
}
app.component.ts
import { Component } from '@angular/core';
// Usage of wordcount pipe within interpolation
@Component({
selector: 'app-root',
template: `
<div style="text-align:center">
<img width="200" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
<p> Word Counter Pipe in action below</p>
<h1>{{ customText | wordcount }}</h1>
</div>
`
})
export class AppComponent {
customText: string = "Java is to JavaScript what car is to Carpet.";
}
Check our newly created custom Angular word counter Pipe in action below.