【问题标题】:How do I sort a material table with favorites on top?如何对带有收藏夹的材料表进行排序?
【发布时间】:2021-12-26 22:11:15
【问题描述】:

我想在 Angular 中对 mat-table(或搜索引擎的 MatTable)进行排序,并将“最喜欢的”项目放在顶部。

无论当前设置什么排序,我都希望最喜欢的项目始终是表格的第一个项目。

我在网上查了一下,但没有找到,所以我不得不自己做。

【问题讨论】:

    标签: angular sorting favorites


    【解决方案1】:

    这是我的解决方案: https://stackblitz.com/edit/angular-defaultsort-zgwgpv

    这里是实现的主要部分。

    将排序重定向到名为sortData 的方法中。在这里我可以随意对数据进行排序:

    <table
      matSort
      (matSortChange)="sortData($event)"
      matSortActive="carbs"
      matSortDirection="asc"
    >
    

    该方法处理sort变量并调用方法sortIt

    sortData(sort: Sort) {
      const data = this.desserts.slice();
      if (!sort.active || sort.direction === '') {
        // initially
        this.sortIt('', true, data);
        return;
      }
    
      this.sortIt(sort.active, sort.direction === 'asc', data);
    }
    

    sortIt 方法对所需的比较器进行排序和调用。主要的是,我检查了 3 个不同的状态:两个项目都是收藏夹(在“顶部”最喜欢的部分排序),只有一个项目是最喜欢的(在这种情况下,最喜欢的是“在”“正常”一个之前),第三个是当两个项目都是“正常”项目时,在这种情况下,我按不同的属性排序。

    sortIt(property: string, isAsc: boolean, data: Dessert[]): void {
      this.sortedData = data.sort((a, b) => {
        if (FAVORITES_FIRST) {
          if (a.favorite && b.favorite) {
            return this.sortByBothFavorites(property, isAsc, a, b);
          }
          // if only one favorite, the favorite is on top, no matter asc or desc
          if (a.favorite === true) {
            return -1;
          } else if (b.favorite === true) {
            return 1;
          }
        }
    
        // if no favorite, standard sorting
        return this.stdSort(property, isAsc, a, b);
      });
    }
    

    这就是诀窍!玩得开心!

    【讨论】:

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