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) =>newDate(a.date).getTime() - newDate(b.date).getTime()
    );
}

Solution 2:

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

@Pipe({
  name: 'sortByDate'
})
exportclassSortByDatePipeimplementsPipeTransform {
  transform(value: any, args?: any): any {
    const sortedValues = value.sort((a, b) =>newDate(b.createdOn).getTime() - newDate(a.createdOn).getTime());
    return sortedValues;
  }
}

Solution 3:

sort-list.pipe.ts

import { Pipe, PipeTransform } from'@angular/core';
@Pipe({
  name: 'sortList'
})
exportclassSortListPipeimplementsPipeTransform {
  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(newDate(a[column]));
                let right = Number(newDate(b[column]));
                return (direction === "-") ? right - left : left - right;
        });
        return value;
    }
}

product-list.component.html

/*Ascending Order:create_dateDescending Order:-create_date*/<ul><li*ngFor="letitemofproductList|sortList :'-create_date'></ul>

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