这是我的代码:
<div *ngFor="let conv of lender.conversation | orderBy" class="conv-single">
{{conv.date | date: 'dd/MM/yyyy | j'}} - {{conv.text}}
</div>
我有这样的对象:
[{
date: somedate,
text: "text1"
}
...]
这是我的orderBy管道:
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(value: any, args?: any): any {
let newVal = value.sort((a: any, b: any) => {
let date1 = new Date(a.date);
let date2 = new Date(b.date);
if (date1 > date2) {
return 1;
} else if (date1 < date2) {
return -1;
} else {
return 0;
}
});
return newVal;
}
}
问题是我总是以相同的顺序获得元素,任何人都知道什么是问题?
答案 0 :(得分:8)
强烈建议不要根据Angular文档使用此类管道。 见https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
您可以尝试这样的事情:
ngOnInit() {
this.sortedItems = items.sort((a: any, b: any) =>
new Date(a.date).getTime() - new Date(b.date).getTime()
);
}
答案 1 :(得分:0)
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>
答案 2 :(得分:0)
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;
}
}