我可以使用 MatTable 按选定的行进行排序吗?

Iva*_*S95 5 typescript angular-material angular mat-table

我有一个 MatTable,它实现了 Angular Material文档中所示的选择

一切工作正常,做出选择等等;但我在想是否可以应用某种排序,以便我可以对数据源进行排序,以便首先显示选定的行。

<table mat-table matSort [dataSource]="dataSourcePPC" class="w-100 table-bordered table-hover">
   <ng-container matColumnDef="select">
       <th mat-header-cell *matHeaderCellDef></th>
       <td mat-cell *matCellDef="let row" class="text-center">
          <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selectionPPC.toggle(row) : null;"
                        [checked]="selectionPPC.isSelected(row)">
          </mat-checkbox>
       </td>
   </ng-container>
   <ng-container matColumnDef="type">
       <th mat-header-cell *matHeaderCellDef mat-sort-header> Type </th>
       <td mat-cell *matCellDef="let ppc">{{ ppcTypeModel[ppc.type] }}</td>
   </ng-container>

   ...

   <tr mat-header-row *matHeaderRowDef="displayedColumnsPPC"></tr>
   <tr mat-row *matRowDef="let row; columns: displayedColumnsPPC;" [ngClass]="{'selected': selectionPPC.isSelected(row)}" (click)="selectionPPC.toggle(row)"></tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我正在研究这个sortingDataAccesor函数,但我真的不明白它是如何工作的;任何有关这方面的帮助表示赞赏。

Vat*_*ato 5

你可以做这样的事情。

这就是复选框的工作原理。

  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef>
      <mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()"
        [indeterminate]="selection.hasValue() && !isAllSelected()" [aria-label]="checkboxLabel()">
      </mat-checkbox>
      <div mat-sort-header>
        <mat-icon>ac_unit</mat-icon>
      </div>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null"
        [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)">
      </mat-checkbox>
    </td>
  </ng-container>
Run Code Online (Sandbox Code Playgroud)

并用打字稿书写。

this.dataSource.sortingDataAccessor = (item, property) => {
        switch (property) {
          case 'select': return this.selection.selected.includes(item);
          case 'nestedObject': return item.parentObject.childObject;
          default: return item[property];
        }
      };
Run Code Online (Sandbox Code Playgroud)

基本上,因为当数据传递给 sortingDataAccessor 时我的 matColumnDef 是“select”,所以您需要检查它是否与“select”匹配。一旦您知道它与“select”匹配,您就可以检查您的项目(即当前行)是否包含在所选项目的数组(selection.selected array)中。

selection = new SelectionModel(true, []); // you already should have this since you have select.
Run Code Online (Sandbox Code Playgroud)

我还介绍了如何对嵌套对象进行排序。如果你需要的话。如果您有嵌套对象,则需要在 switchcase 中编写类似 case 'nestedObject' 的内容。“nestedObject”就是您在表中对列的称呼。

我在我的项目中检查了它并且工作正常。

祝你好运!