单击按钮在 Ascending/Descending 中对 Angular 中的数据进行排序

Sorting Data in Angular in Ascending/Descending on click of a button

我有一个 (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>

我想要的是单击按钮Ascending/Descending 时应该对它进行排序。但是它只会对基于数据的升序排序 only.I 不要知道我哪里做错了。

您好像忘记拨动开关了:

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));
}