【问题标题】:Sorting Angular table without using Materials, just sort method?在不使用材料的情况下对 Angular 表进行排序,只是排序方法?
【发布时间】:2019-02-28 19:50:01
【问题描述】:

table.component.html

当我点击标题时,该功能必须对所有列进行 ASC/DESC 排序。

<table>
<tr>
  <th *ngFor="let col of columns" (click)="sortTable(col)">{{col}}</th>
</tr>
<tr *ngFor="let user of users">
  <td *ngFor="let col of columns">{{user[col]}}</td>
</tr>
</table>

table.component.ts

sortTable(param) 方法仅适用于 ASC,我无法为 DESC 再次单击同一个标题,因此在我单击另一个标题之前它保持不变。

export class DynamicTableComponent implements OnInit {
@Input()
users = [];
@Input()
columns: string[];

constructor() { }

    sortTable(param) {
    this.users.sort((a, b) =>
      (a[param] > b[param]) ? 1 :
        ((b[param] > a[param]) ? -1 :
          0));
  }

【问题讨论】:

  • @TheHeadRush 我看到了你的链接,它很有帮助......我搜索了所有内容。现在我解决了数字列的问题,正如您在我的编辑文档中看到的那样。 DESC排序的问题仍然存在,只是ASC,有什么建议吗?
  • 当您调用array.sort 时附加reverse。使用提供的答案中的变量,例如objs.sort(compare).reverse()
  • @TheHeadRush 我需要一些自动的东西,当是 ASC 或 DESC 时 +1/-1。我在那个链接上看到了一些东西,但没有任何效果......
  • @TheHeadRush 好的,完成,我现在将回答我自己的问题。谢谢!

标签: angular sorting frontend


【解决方案1】:

您是否考虑过使用现有管道进行排序而不是自己编写? 例如:https://github.com/danrevah/ngx-pipes

更直接的是,这个: https://github.com/danrevah/ngx-pipes#orderby

使用该包,您只需要管理单击设置变量来确定 orderby 以及它是 ASC 还是 DESC,如前缀所示。

来自 Docs 的 EG:

<!-- Returns array ordered by value of property -->
<p>{{ deepObj | orderBy: 'amount' }}</p>  
<!-- Output: [{id: 3, ...}, {id: 4, ...}, {id: 2, ...}, {id: 1, ...}] -->
<p>{{ deepObj | orderBy: '-amount' }}</p>  
<!-- Output: [{id: 1, ...}, {id: 2, ...}, {id: 4, ...}, {id: 3, ...}] -->

【讨论】:

    【解决方案2】:

    我在使用反向排序时遇到了问题,所以我喜欢这个并且它有效!

    export class DynamicTableComponent implements OnInit {
      @Input()
      users = [];
      @Input()
      columns: string[];
    
      direction = false;
    
      sortTable(param) {
        this.direction = !this.direction;
        const compare = (a, b) => {
            if (!a[param] && !b[param]) {
              return 0;
            } else if (a[param] && !b[param]) {
              return -1;
            } else if (!a[param] && b[param]) {
              return 1;
            } else {
              const value1 = a[param].toString().toUpperCase(); // ignore upper and lowercase
              const value2 = b[param].toString().toUpperCase(); // ignore upper and lowercase
              if (value1 < value2) {
                return !this.direction ? -1 : 1;
              } else if (value1 > value2) {
                return !this.direction ? 1 : -1;
              } else {
                return 0;
              }
            }
          };
        return this.users.sort(compare);
        //this.users = MYITEMS
        }
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2018-09-13
      • 2017-05-07
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2022-12-10
      相关资源
      最近更新 更多