Мне нужно отсортировать MatTableDataSource
, чтобы сначала отобразить строки с установленным флажком, а затем строки не отмечены.
Я видел, что сортировка datasource
зависит от имени заголовка MatColumnDef
(id ) и asc | des c (начало), но это не может мне помочь. Я попытался отсортировать по 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
, но в идеале я хотел бы сделать это в методе запроса после всех записей с сервера были отброшены в коллекцию.
Спасибо за вашу помощь