我试图在表格结构中迭代数组值,我希望根据名称,城市等各种标题进行排序......我无法正确排序数据。请指导我。我已经尝试将城市名称存储在一个单独的数组中并迭代相同的数组以在UI中显示城市名称,但它显示了每一行中的所有城市。请建议一个正确的方法。
employees: Array < any > ;
column: string = 'city';
arr: any;
ngOnInit() {
this.allservice.geturl(this.tableurl)
.subscribe(
resEmployeeData => {
this.employees = resEmployeeData.data
for (let i = 0; i < this.employees.length; i++) {
this.arr[i].push(this.employees[i].city)
}
console.log(this.arr)
},
)
this.sort(this.column);
}
sort(property) {
console.log(property)
this.isDesc = !this.isDesc;
this.column = property;
this.direction = this.isDesc ? 1 : -1;
};
&#13;
<table align="center" class="table">
<thead>
<tr>
<th class="pointer" (click)="sort(userResponse.firstName)">
<i class="fa" [ngClass]="{'fa-sort': column != 'userResponse.firstName', 'fa-sort-asc': (column == 'userResponse.firstName' && isDesc), 'fa-sort-desc': (column == 'userResponse.firstName' && !isDesc) }" aria-hidden="true"> </i> FIRST NAME </th>
<th class="pointer" (click)="sort(arr)">
<i class="fa" [ngClass]="{'fa-sort': column != 'city', 'fa-sort-asc': (column == 'city' && isDesc), 'fa-sort-desc': (column == 'city' && !isDesc) }" aria-hidden="true"> </i> CITY </th>
<th class="pointer" (click)="sort(email)">
<i class="fa" [ngClass]="{'fa-sort': column != 'email', 'fa-sort-asc': (column == 'email' && isDesc), 'fa-sort-desc': (column == 'email' && !isDesc) }" aria-hidden="true"> </i> EMAIL </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees| paginate: { itemsPerPage: 5, currentPage: p }| category: searchText | orderBy: {property: column, direction:direction}">
<td>{{employee.userResponse.firstName}}</td>
<td> {{employee.city}}</td>
<td> {{employee.email}}</td>
</tr>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
</tbody>
</table>
&#13;
答案 0 :(得分:0)
如果您的排序标准是静态的,您可以将ngOnInit修改为以下内容:
ngOnInit() {
this.allservice.geturl(this.tableurl)
.subscribe(resEmployeeData => {
this.employees = resEmployeeData.data
for (let i = 0; i < this.employees.length; i++) {
this.arr[i].push(this.employees[i])
}
// Because your array is made using the city you don't need to specify anything
this.arr.sort((elemA, elemB) => {
return elemA.city - elemB.city;
});
});
}
在这种情况下,this.arr.sort();
将按字母顺序缩短数组元素(排序方法的默认行为)。如果您想按其他条件排序,可以传递函数,请查看sort method documentation。
在你的模板中:
<tr *ngFor="let employee of arr">
<td>{{employee.userResponse.firstName}}</td>
<td> {{employee.city}}</td>
<td> {{employee.email}}</td>
</tr>