我有一个 (click)
调用一个 sortUser()
函数对数据进行排序。
我的 HTML 看起来像这样。
let isAscendingSort: Boolean = true;
sortUser() {
console.log('sorting!'); //just to check if sorting is beng called
this.items.sort((item1: any, item2: any) => this.compare(item1, item2));
}
// Sort
compare(item1: any, item2: any): number {
let compValue = 0;
compValue = item1.attributes.fullName.localeCompare(item2.attributes.fullName, 'en', {
sensitivity: 'base'
});
console.log(compValue);
if (!this.isAscendingSort) {
compValue = compValue * -1;
}
return compValue;
}
<button (click)="sortData()">Sort Data</button>
<div *ngFor="let item of items">
{{items.attributes.fullName}}
</div>
我想要的是它应该在单击按钮时按升序/降序排序。但它只会对基于升序排序的数据进行排序。我不知道我做错了什么。 p>
最佳答案
好像你忘了拨动开关:
private isAscendingSort: boolean = false;
sortUser() {
console.log('sorting!'); // just to check if sorting is being called
this.isAscendingSort = !this.isAscendingSort; // you missed this
this.items.sort((item1: any, item2: any) => this.compare(item1, item2));
}
关于javascript - 单击按钮以升序/降序对 Angular 中的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276246/