[英]How to sort a list correctly in Angular?
我有以下簡單的排序算法:在我的 HTML 文件中,我從 JSON 中獲取表的列名,我想對其進行上下排序。 使用方法 sortData 應根據所選列執行排序。 但是,該列表未排序。
<ion-row>
<ion-col style="width: 5em;" *ngFor="let column of columnsHeader.controls " (click)="sortData(column.name)">
<div class="table__header" id="hoverId">{{column.name}}</div>
</ion-col>
<ion-col style="width: 3em;">
<div class="table__header"></div>
</ion-col>
</ion-row>
我在 page.ts 中的排序算法
sortData(value: any){
console.log(value);
if (this.sortColumn) {
const newarr = this.tableInformation.sort((a, b) => a.value - b.value);
this.tableInformation = newarr;
}
else {
const newarr = this.tableInformation.sort((a, b)=> b.value - a.value);
this.tableInformation= newarr;
}
this.sortColumn=!this.sortColumn;
console.log(this.sortColumn);
console.log(this.tableInformation);
}
console.log(value) 正確地為我提供了所需的列名。 但是,我的列表不能按值排序。 但是,如果我硬編碼我的排序算法並輸入例如 id 或其他列名,那么我的列表將按硬編碼的名稱排序。 除非該列具有字符串值,否則不幸的是它也不起作用。
sortData(value: any){
console.log(value);
if (this.sortColumn) {
const newarr = this.tableInformation.sort((a, b) => a.id - b.id);
this.tableInformation = newarr;
}
else {
const newarr = this.tableInformation.sort((a, b)=> b.id - a.id);
this.tableInformation= newarr;
}
this.sortColumn=!this.sortColumn;
console.log(this.sortColumn);
console.log(this.tableInformation);
}
現在我的問題:
提前致謝。
a.value - b.value
查找 a 和 b 上的屬性value
,這可能是未定義的
您可能想要使用a[value] - b[value]
對於箭頭,您可以使用<ion-icon name="arrow-down-outline"></ion-icon>
與<ion-icon *ngIf="sortingAscended(colname)" name="arrow-up-outline"></ion-icon>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.