Angular 14 Tutorial- How To create Custom Pipe In Angular 14 Application

Angular Custom Pipe Tutorial– In this tutorial, we will learn about Angular default and custom pipes. Angular offers tons of built-in pipes that help us deal with various types of programming problems while developing single-page web applications.

This Angular tutorial is compatible with version 4+ including latest version 12, 11, 10, 9, 8 ,7, 6 & 5.

 

We will also learn how to create Angular Pipe from scratch. Now, let’s get started:

 

Angular 14 Pipe Example

  • Working With Angular Pipes
  • Angular built-in Pipes
  • Creating Custom Pipe In Angular

 

Getting Started

Pipes in Angular are quite useful when it comes to managing data within the interpolation “{{|}}”. In Angular1, pipes were referred to as filters but now, they are famous for the name pipes.

 

In order to transform the data, we use the character |. Check out the syntax for the same below:

{{ i will become uppercase one day | uppercase }}

Pipes accept data, arrays, strings and integers as inputs. Inputs are separated with |. Later, the inputs will be converted into the desired format before displaying them in the browser.

We will be looking at a few examples involving pipes.

In the below example, we are trying to display the given text in uppercase. We 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";
}

 

We will find the below 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>

 

We will see the below image in the browser:

Angular 2 Pipes Example

 

Angular built-in Pipes

Angular pipes help us to reconstruct data instantly in our Angular app. Angular offers some built-in pipes API to update our data in a few seconds. It also allows us to create custom pipes in our app. Below given are some of the Angular pipes:

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 App

Now, we will learn how to use built-in Angular pipes:

 

Async Pipe

The Async Pipe is considered the best practice when we 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 is 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 data in Angular:

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 formulates 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. The 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.stringyfy method :

{{ 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 A Custom Pipe In Angular App

Here, we will learn how to create a Custom Pipe. We have to run the below command in order to do so:

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 the 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, we will write the logic for the word counter in a string in Angular using the PIPE API service.

We need to open the wordcount.pipe.ts file and use the below code into it:

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.";
}

 

Finally, in the browser, we would be able to see the below image:

Angular Word Counter Pipe

Leave a Reply

Your email address will not be published. Required fields are marked *