javascript - 单击按钮以升序/降序对 Angular 中的数据进行排序

标签 javascript typescript angular5 angular6 angular7

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

相关文章:

javascript - JQuery ajax 使用复选框对象回发 id

Angular[karma] Observable 上的异步测试

c# - C# 和 typescript 之间 JSON 的端到端类型安全

html - Angular 6 是否正在删除默认元素边距?

html - Angular 5 按钮提交按回车键

javascript - Socket.io,从客户端获得两个响应然后运行代码?

javascript - 在 POST 之前获取表单下拉值?

javascript - 使用 Angular 5 发送自定义 header

javascript - Three.js 从相机中提取以弧度为单位的旋转

Typescript 错误作为警告