javascript - 按日期排序 Angular 2 管道

标签 javascript angular

这是我的代码:

<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/

相关文章:

javascript - 错误类型错误 : Cannot read property 'invalid' of undefined while trying to list FormArray of FormGroups in Angular

Angular 2,主要组件内的组件

angular - punycode 使用箭头函数编译并使其无法在 ie 11 中呈现

javascript - 仅 Android 浏览器 : canvas. toDataURL 抛出未捕获错误:SecurityError:DOM 异常 18

javascript - 我应该如何使用 JQuery 更改鼠标悬停时 DOM 元素的背景颜色?

javascript - 如何控制全页半透明覆盖div顶部图像的css

angularjs - 降级 Angular js 的所有 Angular 组件的优雅方法

javascript - 是否需要检查正则表达式匹配长度以确定是否至少有一个匹配?

javascript - 使用 ES5 的固定数据表示例

angular - 如何从Observable模拟错误而不会崩溃?