【发布时间】:2019-12-06 13:06:19
【问题描述】:
我正在尝试将 matSort 添加到这个已经工作和现有的 MatTable 中。我已经尝试实现我在 mat-sort not working on mat-table 的其他线程上找到的内容,因为它看起来像是在描述同样的问题,但无法让它发挥作用。我相信原因之一可能是我的数据源是在模板中异步计算的,而不是在我认为的 TS 文件中。 为了清楚起见,我之前更改了检索数据源的方式,将其移至 TS 文件,但 UI 仍然没有更新。
这里是简化版的代码:
模板:
<table matSort mat-table [dataSource]="(searchMode === 'shift') ? shifts : (searchMode === 'booking') ? bookings">
<ng-container matColumnDef="orgName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Organisation </th>
<td mat-cell *matCellDef="let element"> {{element.orgName}} </td>
</ng-container>
<ng-container matColumnDef="workerName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Worker </th>
<td mat-cell *matCellDef="let element"> {{element.workerName}} </td>
</ng-container>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20, 50, 100]" [pageSize]="20" [length]="total" (page)="onPageChange()" showFirstLastButtons></mat-paginator>
TS 文件:
import {MatTable, MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
export class TsGenerationSearchTableComponent implements OnInit, OnChanges, AfterViewInit {
dataSource = new MatTableDataSource<Shift>();
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
@ViewChild(MatSort, {static: false}) sort: MatSort;
selectedWeekend: string;
selectedWeekStart: string;
ngOnInit() {
this.dataSource.paginator = this.paginator;
}
ngAfterViewInit(): void {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
onPageChange() {
const data: GetShiftTimesheetData = {
action: (this.searchMode === 'shift') ? 'PageGetShiftsForTsAction' : (this.searchMode === 'booking') ? 'PageGetBookingsForTsAction',
weekStartDate: this.selectedWeekStart,
weekEndDate: this.selectedWeekend,
paginator: {
pageSize: this.paginator.pageSize,
pageIndex: this.paginator.pageIndex
}
};
this.search.emit(data);
}
排序绝对不会在 UI 中显示任何内容。我尝试订阅ngOnChanges,看看它是否至少被看到,像这样:
ngOnChanges(changes: SimpleChanges): void {
if (this.dataSource && this.paginator && this.sort) {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.sort.sortChange.subscribe(val => {
console.log(val);
});
}
}
并且日志显示它至少对sortChange做出反应:
{active: "workerName", direction: "asc"}
和
{active: "workerName", direction: "desc"}
但在 UI 中什么都没有。我试过在订阅中做this.dataSource.sort = val;,但抛出错误ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
欢迎任何帮助/提示。非常感谢你们。
【问题讨论】:
标签: angular asynchronous angular-material datasource mat-table