Skip to content Skip to sidebar Skip to footer

Sort By Date Angular 2 Pipe

Here is my code:
{{conv.date | date: 'dd/MM/yyyy | j'}} - {{conv.text}}
I have

Solution 1:

It is strongly suggested not to use such pipes according to Angular Documentation. See https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

You can try something like this:

ngOnInit() {
    this.sortedItems = items.sort((a: any, b: any) =>
        new Date(a.date).getTime() - new Date(b.date).getTime()
    );
}

Solution 2:

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

@Pipe({
  name: 'sortByDate'
})
export class SortByDatePipe implements PipeTransform {
  transform(value: any, args?: any): any {
    const sortedValues = value.sort((a, b) => new Date(b.createdOn).getTime() - new Date(a.createdOn).getTime());
    return sortedValues;
  }
}

Solution 3:

sort-list.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'sortList'
})
export class SortListPipe implements PipeTransform {
  transform(value: any, args?: any): any {
        if (typeof args[0] === "undefined") {
                return value;
        }
        let direction = args[0][0];
        let column = args.replace('-','');
        value.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 value;
    }
}

product-list.component.html

/*
Ascending Order: create_date
Descending Order: -create_date
*/
<ul>
    <li *ngFor="let item of productList | sortList : '-create_date'>
</ul>

Post a Comment for "Sort By Date Angular 2 Pipe"