首页 > 解决方案 > MatTableDatasource 的自定义排序数据源:首先选中复选框

问题描述

我需要对 a 进行排序MatTableDataSource,以便首先显示选中复选框的行,然后显示未选中的行。

我看到排序datasource取决于MatColumnDef标题名称(id)和 asc|desc(开始),但这对我没有帮助。我试图排序,dataSource.data因为我有isSelected.

这是我尝试过的,但不起作用

HTML

<button (click)="sortDataSource('createdDate', 'asc')">
  <span>isSelected</span><mat-icon>arrow_upward</mat-icon>
</button>
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
  <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>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? singleToggle(row) : null" [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)">
      </mat-checkbox>
    </td>
  </ng-container>
  <ng-container matColumnDef="privId">

  ...

打字稿

@ViewChild(MatSort, { static: false }) matSort: MatSort;

sortDataSource(id: string, start: 'asc' | 'desc') {
  const matSort = this.dataSource.sort;

  this.dataSource.data.sort((a: any, b: any) => {
    if (a.isSelected && !b.isSelected) {
      return -1;
    } else if (!a.isSelected && b.isSelected) {
      return 1;
    } else {
      return 0;
    }
  });

  this.dataSource.sort = this.matSort;
}

query(q?) {
  this.privs = [];
  if (q) {
    this.query = q;
  }
  this.neo4jService.httpNeo4jRun(this.query, null)
    .subscribe((r) => {
      // console.log(r); // this.checkBox);
      JSON.parse(JSON.stringify(r.records)).forEach(node => {
        this.privs.push(node._fields[0].properties)
      });
      this.dataSource = new MatTableDataSource(this.privs);
      if (this.selectedPriv && this.selectedPriv.length > 0) {
        this.selection = new SelectionModel < Priv > (true, this.privs.filter(p => this.selectedPriv.find(e => e.privCode == p.privCode) ? true : false));
      }
      this.dataSource.sort = this.sort;
      // this.sortDataSource('privName', 'asc');
      this.dataSource.paginator = this.paginator;
    });
}

目前我手动触发sortDataSource但理想情况下我想在服务器的所有记录都被推送到集合中之后在查询方法中执行它。

谢谢你的帮助

标签: angularangular-material

解决方案


推荐阅读