我在 Angular2 中对对象数组进行排序时遇到问题。
对象看起来像:
[
{
"name": "t10",
"ts": 1476778297100,
"value": "32.339264",
"xid": "DP_049908"
},
{
"name": "t17",
"ts": 1476778341100,
"value": "true",
"xid": "DP_693259"
},
{
"name": "t16",
"ts": 1476778341100,
"value": "true",
"xid": "DP_891890"
}
]
并且存储在 values
变量中。
我只想让 *ngFor
循环按 name
属性对其进行排序。
<table *ngIf="values.length">
<tr *ngFor="let elem of values">
<td>{{ elem.name }}</td>
<td>{{ elem.ts }}</td>
<td>{{ elem.value }}</td>
</tr>
</table>
尝试用管道来做,但惨遭失败。 任何帮助表示赞赏。
Plunker 链接:https://plnkr.co/edit/e9laTBnqJKb8VzhHEBmn?p=preview
编辑
我的 pipe :
import {Component, Inject, OnInit, Pipe, PipeTransform} from '@angular/core';
@Component({
selector: 'watchlist',
templateUrl: './watchlist.component.html',
styleUrls: ['./watchlist.component.css'],
pipes: [ ArraySortPipe ]
})
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
然后将 pipe
名称放入 html 文件中:
<tr *ngFor="let elem of values | sort">
最佳答案
虽然您可以使用管道解决这个问题,但您必须问问自己,管道的可重用性在您的特定项目中是否对您有用。以后会不会经常需要在其他数组或其他组件上按“name”键对对象进行排序?这些数据是否会经常变化,并且会以难以简单地在组件中排序的方式变化?您是否需要根据 View 或输入的任何更改对数组进行排序?
我创建了一个经过编辑的 plunker,其中数组在组件的构造函数中排序,但没有理由不能将此功能移出到它自己的方法(例如 sortValuesArray)中,以便在必要时重新使用。
constructor() {
this.values.sort((a, b) => {
if (a.name < b.name) return -1;
else if (a.name > b.name) return 1;
else return 0;
});
}
关于javascript - 对 Angular2 中的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103733/