Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Creating a Custom Pipe in Ionic

Ionic custom pipe

Pipe’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. In the ionic Angular project, we will demonstrate custom pipes in ionic with examples.

Create project for Custom pipe in Ionic

Step 1: Let first create an Ionic custom pipe project.

ionic start customPipe blank --type=angular
cd customPipe

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

We’ll demonstrate Here’s a quick screenshot of what we’ll be building.

custom pipe in ionic
Custom Pipe in Ionic

Step 2: Run the following command to create a pipe

ionic generate pipe userExtract

Step 3: Create a folder pipe inside the app and move all generated pipe files in the pipes folder. Add the following code in the app/pipes/custom.pipe.ts file to create a folder pipe inside the 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 that 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 references of pipe inside this pipe module. Some projects may contain more than one pipe. Add the following code in the 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 turn the value in front of it to input. If any reference to the pipe is created automatically in the app.module.ts file while the run pipe generates the command, then you can remove it.

Step 3: Add the following code in home.ts, Is a good practice to move all pages into the pages folder. Create a separate folder called pages in the app folder and move the home page in the app folder. And we also have to add a page in front of the 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>

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

Step 5: In home.module.ts we have to add the pipes module. Add the following code in the 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 {}

More information on the angular pipe is in the official documentation.

Related posts

Creating a Custom Pipe in Ionic

Leave a Reply

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

Scroll to top