Angular Material 2:多重 mat-table 排序仅在第一个 table 上起作用

Angular Material 2: Multiple mat-table sorting is working on first table only

我在我的应用程序中使用了 Angular Material,我有两个 mat-table 对单个组件进行排序,但我的排序只对第一个 table

有效

这是ts代码

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild(MatSort) additionalDataSort: MatSort;
@ViewChild(MatPaginator) additionalDataPaginator: MatPaginator;
ngAfterViewInit() {
    this.inventoryDataSource.sort = this.inventoryDataSort;
    this.inventoryDataSource.paginator = this.inventoryDataPaginator;
    this.additionalDataSource.sort = this.additionalDataSort;
    this.additionalDataSource.paginator = this.additionalDataPaginator;
}

垫-table

<mat-table #table1 [dataSource]="inventoryDataSource" matSort>
<mat-table #table2 [dataSource]="additionalDataSource" matSort>

ViewChild 中的选择器查询 DOM 并找到第一个数学。你能试着把这部分从

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild(MatSort) additionalDataSort: MatSort;
@ViewChild(MatPaginator) additionalDataPaginator: MatPaginator;

@ViewChild(MatSort) inventoryDataSort: MatSort;
@ViewChild(MatPaginator) inventoryDataPaginator: MatPaginator;

@ViewChild('table2', {read: MatSort}) additionalDataSort: MatSort;
@ViewChild('table2', {read: MatPaginator}) additionalDataPaginator: MatPaginator;

我已经在 similar question 中回答了这个问题,但我也会在这里 post 回答这个问题。它可能会帮助另一个可怜的灵魂。

使用 Angular v.8.2.0.

我假设所有必需的属性都已使用且正确(mat-sortmat-table[dataSource]matColumnDefmat-sort-header 等)。

我有一个简单的组件,有两个 sortable table(为简洁起见,我省略了不相关的代码)。

每个 table 在模板中都有一个唯一的 ref 属性。例如:

<table #table1>
<table #table2>

然后,在组件中,我为每个排序器使用 @ViewChild 装饰器:

@ViewChild('table1', { read: MatSort, static: true }) sort1: MatSort;
@ViewChild('table2', { read: MatSort, static: true }) sort2: MatSort;

这里read属性很重要。不要错过!

然后(在 ngOnInit 中),我将排序器分配给每个 table 数据源,如官方文档所示:

this.dataSource1.sort = this.sort1;
this.dataSource2.sort = this.sort2;