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

北城以北 提交于 2019-12-12 12:14:23

问题


I have used Angular Material in my application and I have two mat-table with sorting on single component but my sorting is working only on first table

here is ts code

@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;
}

mat-table

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

回答1:


Selector in ViewChild queries DOM and it finds first math. Could you try change this part from

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

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

to

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

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



回答2:


I have already answered this in a similar question, but I will post it here also. It might help another poor soul.

Using Angular v.8.2.0.

I am assuming that all required attributes are used and correct (mat-sort, mat-table, [dataSource], matColumnDef, mat-sort-header, etc).

I have a simple component with two sortable tables (I omitted the irrelevant code for brevity).

Each of the tables has an unique ref attribute in the template. For example:

<table #table1>
<table #table2>

Then, in the component, I use the @ViewChild decorator for each of the sorters:

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

The read property is very important here. Don't miss it!

Then (in ngOnInit), I assign the sorters to each table data source as shown in the offical docs:

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


来源:https://stackoverflow.com/questions/47691186/angular-material-2-multiple-mat-table-sorting-is-working-on-first-table-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!