如何使用 Angular2 管道按最接近今天的日期排序

Kes*_*vid 1 html javascript sorting angular2-pipe angular

假设我有一个Event集合:

export class Event {
  startingTime: Date
}
Run Code Online (Sandbox Code Playgroud)

我想从最接近今天的位置开始显示它们,那OrderByUpcomingToLatestPipe会是什么样子?

<event-element *ngFor="let event of events | orderByUpcomingToLatest"></event-element>

编辑:

当离今天最近的日期是第一个,离今天最远的日期是最后一个时,我希望数组按降序排列(已经过去的日期将以相同的方式排在最远的日期之后)

And*_*aru 5

不要使用管道进行订购。来自Pipes 文档的片段:

附录:无 FilterPipe 或 OrderByPipe

Angular 不提供用于过滤或排序列表的管道。熟悉 AngularJS 的开发人员将它们称为 filter 和 orderBy。在 Angular 中没有等价物。

这不是疏忽。Angular 不提供这样的管道,因为它们性能很差并且会阻止激进的缩小。filter 和 orderBy 都需要引用对象属性的参数。在本页的前面部分,您了解到此类管道必须是不纯的,并且 Angular 几乎在每个变更检测周期中都会调用不纯的管道。

你应该在你的服务或组件中对你的事件进行排序,可能使用类似Lodash 的东西:

import * as _ from 'lodash';

this.sortedEvents = _.sortBy(this.events, e => p.startingTime);
Run Code Online (Sandbox Code Playgroud)

然后在您的模板中:

<event-element *ngFor="let event of sortedEvents"></event-element>
Run Code Online (Sandbox Code Playgroud)