Creating a Custom Pipe in Ionic 4

omponentPipe’s are one of the important features of Angular. Angular comes with a stock of pre-built pipes such as Date Pipe, UpperCasePipe, LowerCasePipe, CurrencyPipe and PercentPipe and so many. Angular allows us to create our own pipe.
The syntax for creating a pipe in command prompt.
ionic -g pipe name-of-pipe-here

The pipe is a class whose sole purpose is to use a method to transform a given value or set of value. The pipe will help us to display in a different format without changing its value. We will create our own pipe with help of @Pipe decorator.

Screen shot of our app.

We this example we do not accept any value from the user, just for demo purpose we are using dummy data in our apps.

Step 1: ionic start CustomPipe blank
Step 2: Run following command to create pipe
ionic generate pipe custom

Step 3:
Create a folder pipes inside app and move all generated pipe files in pipes folder. Add the following code in app/pipes/custom.pipe.ts file create a folder pipes inside app folder.

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'userExtract'})

export class UserExtractPipe implements PipeTransform {
 transform(value: any, arg): any {
    let newVal: any;
    if (arg === 'firstname') {
      newVal = value.name ? value.name.split(' ')[0] : '';
    } else if (arg === 'lastname') {
      newVal = value.name ? value.name.split(' ').splice(-1) : '';
    } else if (arg === 'age') {
      const currentTime = new Date();
      newVal = value.birthyear ? currentTime.getFullYear() - value.birthyear : 0;
    }
    return newVal;
  }
}

We have used transform(value:any, arg) is a method of Pipe class which will take two parameters first value is a value from the left side of | pipe symbol, in our case is user variable from home.ts as value and arg is the second argument is the right side of pipe |. To create a custom pipe in ionic we have to import Pipe and PipeTransform from the angular/core.

We will create another file pipes.module.ts inside pipes, will import all reference of pipe inside this pipe module. Some project may contain more than one pipe. Add the following code in app/pipes/pipes.module.ts file

import { NgModule } from '@angular/core';
import { UserExtractPipe } from './custom-pipe.pipe';

@NgModule({
declarations: [UserExtractPipe],
imports: [],
exports: [UserExtractPipe],
})

export class PipesModule {}

In angular, we convert any value to any desired format with the help of an Angular pipe. Angular will detect the sign | as the pipe in the HTML or template and turns the value in front of it to input. If any reference to the pipe is created automatically in app.module.ts file while run pipe generates command, then you can remove it.

Step 3: Add the following code in home.ts, Is good practice to move all page into pages folder. Create a separate folder called pages in the app folder and move home page in the app folder. And we also have to add a page in front of route path in app-routing.module.ts

{ path: ‘home’, loadChildren: ‘./pages/home/home.module#HomePageModule’ },
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  private user: any;

  constructor() {
      this.user = { name: 'John Connor', birthyear: 1985 };
  }
}

Step 4: Add the following code in home.html.

<ion-header>
    <ion-toolbar>
        <ion-title>
            Ionic Pipe
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content padding>
    <h4>Unformatted Value</h4>
    <ion-card>
        <ion-card-header>
            <code>User</code>
        </ion-card-header>
        <ion-card-content>
            {{ user | json }}
        </ion-card-content>
    </ion-card>

    <h4>Formatted Value</h4>
    <ion-list>
        <ion-item>
            <ion-label fixed>First Name</ion-label>
            <ion-note item-right>{{ user | userExtract : "firstname" }}</ion-note>
        </ion-item>
        <ion-item>
            <ion-label fixed>Last Name</ion-label>
            <ion-note item-right>{{ user | userExtract : "lastname" }}</ion-note>
        </ion-item>
        <ion-item>
            <ion-label fixed>Age</ion-label>
            <ion-note item-right>{{ user | userExtract : "age" }}</ion-note>
        </ion-item>
    </ion-list>
</ion-content>

In-home template we have use user | userExtract : “firstname”, where a user is a variable object, userExtract is pipe name and first name is an argument to extract the first name from a user object

Step 5: In home.module.ts we have to add pipes module. Add the following code in home.module.ts file.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { HomePage } from './home.page';
import { PipesModule } from '../../pipes/pipes.module';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ]),
    PipesModule,
  ],
  declarations: [HomePage]
})
export class HomePageModule {}