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

Standard

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';

@Pipe({
    name: 'sortgrid'
})

@Injectable()
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:

@NgModule({
 imports: [
   BrowserModule,
   HttpModule,
   FormsModule,
  ],
 declarations: [
   AppComponent,
   SortGridPipe
  ],
 providers: [
   All_Services
  ],
 bootstrap: [
   AppComponent
  ],
 schemas: [
   CUSTOM_ELEMENTS_SCHEMA
  ]
})

Html code:

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s