是否可以选择在 orderBy 管道中更改按 asc/desc 排序?
数组:
this.testArr = [{name: 'bbb', id: '1'}, {name: 'ccc', id: '2'}, {name: 'aaa', id: '0'}];
在 HTML 中:
<ul><li *ngFor="let item of testArr | orderBy: 'id' : true"><div>{{item.id}}</div></li></ul>
将“true”替换为“false”/“asc”/“desc”不起作用。 所需的输出应为:0, 1, 2,另一个参数为:2, 1, 0。
谢谢。
最佳答案
由于性能和缩小问题,角度指南建议不要使用管道 - https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
首选方法是在组件中具有过滤/排序方法
sortAccounts(prop: string) {
const sorted = this.accounts.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
// asc/desc
if (prop.charAt(0) === '-') { sorted.reverse(); }
return sorted;
}
然后在组件 View 中
<li *ngFor="let a of sortAccounts('id')">
或
<li *ngFor="let a of sortAccounts('-id')">
关于angular5 - 角度 5 ,按升序/降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49476564/