Angular 6/7 | Create Custom Pipes AKA Filters in Angular 2.X

Our applications may have a lot of data for presentation, But for creating a good user experience it is preferable to see in a more understandable format like March 12, 2010 is better to read then Mon Mar 12 2010 15:23:40 GMT-0700 (Pacific Daylight Time).

For such small and repeated tasks of transforming values in other formats we used to use Filters in AngularJS version 1, But after Angular 2 we have pipes which serve similar tasks and once defined can be used anywhere in the application.

We will discuss more Pipes using Angular’s latest stable version 7. Our todo list will have the following tasks for Pipes.

How to Create Simple Custom Pipes?
How to pass parameters in custom Pipes?
How to Use OrderBy Filter Pipe in Angular 5+ Versions?
Other Usefull Custom Angular 2+ Filters/ Pipes

How to Create Simple Custom Pipes?

First, create a new Angular application by running following in CMD Prompt using Angular CLI.

Install NodeJS then Angular CLI as follows

$ npm install -g @angular/cli

Create new Angular project

$ ng new NG7Pipes
$ cd NG7Pipes
$ ng serve --open

As now we have a new project ready, create a new file custom.pipe.ts in the app folder.

import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({
    name:'appendDollar'
})
export class appendDollarPipe implements PipeTransform {
    transform(value:string, pretext:string): string{
        return value+pretext;
    }
}

This is the simplest Pipe which we just created above. This will simply append a $ sign after value we pass then return it.

Add this pipe in app.module.ts file in declarations array.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { appendDollarPipe } from './pipes/appendText.pipe';

@NgModule({
  declarations: [
    AppComponent,
    appendDollarPipe
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

In app.component.ts file, define some value to variable to test our Pipe.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'Angular 7 Pipes';
  costOfMyCoffeeCup:number;

  constructor(){
    this.costOfMyCoffeeCup = 6;
  }
}

In the app.component.html file, we can use the filter as follows

<p>
     {{costOfMyCoffeeCup | appendDollar}}
</p>

This will output as 6$

How to pass parameters in custom Pipes?

In some situations, we may need to pass some parameters with value. To pass parameters we use a colon ( : ) separated values up to any number.

for example, let’s modify above Pipe to take currency name then show output.

@Pipe({
    name:'appendCurrency'
})
export class appendCurrencyPipe implements PipeTransform {
    transform(value:string, currency:string): string{
        return value+currency;
    }
}

In HTML we will change usage as follows

{{costOfMyCoffeeCup | appendCurrency:'EUR'}}

How to Use OrderBy Filter Pipe in Angular 5+ Versions?

According to Angular them, new versions of doesn’t provide filters/ pipes for list ordering. They removed OrderBy filter as it was poor on performance and aggressive minification processes. You can read more about the details here.

But here we will only discuss if Angular not providing it then What to do? Don’t worry we have a solution for it 🙂 We can use nxg-order-pipe package in our application to achieve the same.

How to use Nxg Order Pipe?

This package is very simple to install and use in the application.

Step 1 – Install the package by running the following

$ npm install ngx-order-pipe --save

Step 2 – Import in the app’s main module app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { OrderModule } from 'ngx-order-pipe';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    OrderModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3 – Now its available to be used anywhere in the application.

let’s try it on some dummy Data. In app.component.ts replace the following code

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'Angular 7 Pipes';
  dummyData: any[] = [
    { name: 'G' },
    { name: 'B' },
    { name: 'Z' },
    { name: 'A' },
    { name: 'H' }
  ];

  constructor() { }
}

In app.component.html use, OrderBy Pipe/ Filter as follows

              <ul>
                <li *ngFor="let item of (dummyData | orderBy:'name') ">
                  {{item.name}}
                </li>
              </ul>

Check more advanced usage options here

Indian Rupee (INR ) Currency Filter Pipe in Angular 2 Plus Versions

@Pipe({
    name:'INRCurrency'
})
export class INRCurrencyPipe implements PipeTransform {
    transform(value:number): string{

        value = Math.round(value);
        var result = value.toString().split('.');
        var lastThree = result[0].substring(result[0].length - 3);
        var otherNumbers = result[0].substring(0, result[0].length - 3);
        if (otherNumbers != '' && otherNumbers != '-')
            lastThree = ',' + lastThree;
        var output = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;

        if (result.length > 1) {
            output += "." + result[1];
        }

        return "₹"+output;

    }
}

This will convert 100000000000 into ₹1,00,00,00,00,000

 

Angular Pipes can be used in many ways to reuse logic and transform data on views. Check more details on Angular Pipes here

Leave a Comment

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