这是我的代码:
<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;
}
}
问题是我总是以相同的顺序获取元素有人知道什么是问题吗?
最佳答案
根据 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()
);
}
关于javascript - 按日期排序 Angular 2 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125311/