Angular2: Creating custom sort filter pipe for datetime column ngFor directive


As you are aware of the fact that, Filters in Angular 1.x have been replaced with pipes in Angular2, most of the time we have datetime value in our array of objects(in easy terms dataset), so in order to display our data on front-end in the form of ASC/DESC datetime column, I have implemented a custom sorting pipe, please note that code is customized to handle both Ascending and Descending option

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

    name: 'sortgrid'

export class SortGridPipe implements PipeTransform {
    transform(array: Array<any>, args: string): Array<any> {
        if (typeof args[0] === "undefined") {
            return array;
        let direction = args[0][0];
        let column = args.replace('-','');
        array.sort((a: any, b: any) => {
            let left = Number(new Date(a[column]));
            let right = Number(new Date(b[column]));
            return (direction === "-") ? right - left : left - right;
        return array;

You need to register the pipe within your module:

 imports: [
 declarations: [
 providers: [
 bootstrap: [
 schemas: [

Html code:

<tr *ngFor="let item of mylst | sortgrid: '-createdDate'">
  • ‘-‘ sign with ‘-createdDate’ in above html code will sort data set in Descending manner.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s