【问题标题】:Angular Material table sorting list of IPsIP的Angular Material表排序列表
【发布时间】:2021-03-06 03:29:06
【问题描述】:

Example here

我不确定为什么 Material Table 排序没有正确排序表我在那里做了一个示例 stackblitz。

(预期)最低 IP 首先排序

"10.16.0.8"
"10.16.0.16"
"10.16.0.32"
"10.16.10.35"
"10.16.10.64"
"10.16.10.120"

(预期)然后你点击按钮排序最高,你会得到

"10.16.10.120"
"10.16.10.64"
"10.16.10.35"
"10.16.0.32"
"10.16.0.16"
"10.16.0.8"

但是现在排序时的当前输出可以是:

10.16.0.16
10.16.0.32
10.16.0.8
10.16.10.120
10.16.10.35
10.16.10.64 

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

    排序是通过比较字符串来完成的,和Java一样,它是“字典顺序”的,你可以在post中找到更多信息

    如果要按数值对它们进行排序,则需要删除点,并在视图中仍然显示点的同时对它们进行排序。

    【讨论】:

      【解决方案2】:

      您需要考虑到您是按字母顺序排序的(120 小于 9),因此您需要转换您的 IP 以获得相同的位数

        ipsnormalized = this.ips    //create a string separated by dots each number
                                    //three digits, eg. 1.23.9.10 =>001.023.009.010
          .map(x => x.split("."))
          .map((x: string[]) => {
            return x.map(y => ("000" + y).slice(-3)).join(".");
          })
          .sort()                  //sort
          .map(x => x.split("."))  //remove the "0s"
          .map((x: string[]) => {
            return x.map(y => +y).join(".");
          });
      

      stackblitz

      更新对 Mat-table 进行排序,只为您的数据添加一个新属性

        element = ELEMENT_DATA.map((x: any) => ({
          ...x,
          normalize: x.weight
            .split(".")
            .map((y: string[]) => ("000" + y).slice(-3))
            .join(".")
        }));
        dataSource = new MatTableDataSource(this.element);
      

      并指明要对这个属性进行排序,(这个mat-sort-header="normalize"

          <ng-container matColumnDef="weight" >
              <th mat-header-cell *matHeaderCellDef mat-sort-header="normalize"> Weight</th>
              <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
            </ng-container>
      

      new stackblitz

      【讨论】:

      • 完美!感谢您的帮助!
      • 太棒了!这是一个非常好的修复,我从来没有想过。
      猜你喜欢
      • 2021-01-23
      • 2019-04-02
      • 2023-04-02
      • 2019-08-26
      • 2020-11-17
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2020-06-10
      相关资源
      最近更新 更多