按日期排序Angular 2管道 [英] Sort by date Angular 2 pipe

查看:153
本文介绍了按日期排序Angular 2管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<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" 
}
...]

这是我的订单通过管道:

And here is my orderBy pipe:

@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;
    }

}

问题是我总是以相同的顺序获得元素吗?有人知道这是什么问题吗?

Problem is I always get elements in same order anyone know what is problem?

推荐答案

根据Angular文档,强烈建议不要使用此类管道. 参见 https://angular.io/guide/pipes#appendix-no- filterpipe-or-orderbypipe

It is strongly suggested not to use such pipes according to Angular Documentation. See 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()
    );
}

这篇关于按日期排序Angular 2管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆