【发布时间】:2018-03-24 03:09:25
【问题描述】:
我有一张表格,想在 Angular 中对其进行排序
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Create Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items | orderBy: order:reverse:'case-insensitive':comparator ">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.createDate }}</td>
</tr>
</tbody>
</table>
和数据
this.items = [
{
id: 1,
name: meow,
createDate: Tue Mar 20 14:15:23 MDT 2018
},
{
id:2,
name: meow2,
createDate: Fri Mar 23 14:15:23 MDT 2018
},
{
id:3,
name: meow2,
createDate: Sun Mar 20 14:15:23 MDT 2013
}
]
和 table.component.ts
comparator(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;
}
到目前为止,我正在使用 ngx-sort-pipe https://github.com/VadimDez/ngx-order-pipe
它可以完美地对数字和字符串进行排序。
但是,它也会按字母顺序对日期进行排序。
根据我的数据格式,如何不仅按数字和字符串排序,还按日期排序。
有没有办法按不同的类型进行排序,例如数字、字符串和日期格式?
提前谢谢你。
【问题讨论】:
-
请分享您尝试的代码。
-
日期可以按原样排序,格式为 yyyy-MM-dd 。只是一个想法。
-
@HassanImam 谢谢。我已经把代码
-
@SamwellTarly 非常感谢。它有助于。我只需将通过日期格式更改为 yyyy-MM-dd 即可完美排序。