问题描述
我的组件中有一个下表,
I have a following table in my component,
<table [dataSource]="(searchResults$ | async)?.accounts" mat-table matSort multiTemplateDataRows>
<ng-container matColumnDef="Code">
<th *matHeaderCellDef mat-header-cell mat-sort-header> Account Code</th>
<td *matCellDef="let account" mat-cell> {{account.code}} </td>
</ng-container>
</table>
我在列定义和表级别都保留了 mat-sort 指令.
https://material.angular.io/components/table/examples 中提供的所有示例a> - 当从 TS 文件设置而不是可观察流时,列出数据源.
I have kept mat-sort directive in both the column definition and at table level.
All the examples provided in https://material.angular.io/components/table/examples - lists down dataSource when set from TS file not as observable stream.
推荐答案
我只是因为这个问题纠结了一段时间,所以把它放在这里,希望能节省一些时间.什么对我有用:
Was just banging my head against the wall about this one for a while so putting this here to hopefully save someone some time. What worked for me:
component.ts:
component.ts:
@Input() dataSource;
@ViewChild(MatSort, {static: true}) sort: MatSort;
ngAfterViewInit() {
this.dataSource.subscribe(data => {
this.dataSource = new MatTableDataSource(data);
this.dataSource.sort = this.sort;
});
}
component.html:
component.html:
<app-table [dataSource]="yourService.getData()"></app-table>
确保在将 Observable 传递给 dataSource
时不要使用 async
管道.
Make sure you don't use the async
pipe when passing the Observable to dataSource
.
我是 Angular、TS 和 RxJS 的新手(通常使用 React),所以如果有人发现这种方法有问题,请告诉我!
I'm new to Angular, TS and RxJS (usually work with React) so if anyone sees issues with this approach let me know!
这篇关于当数据源为 Observable<T> 时,如何在 Angular Material Data Table 中启用排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!