i still new with angular and not familiar with it, I have face a problem regarding mat table for sorting. i have multi table in one page, each table we separated with mat tab, the problem is , the sorting only working on first table("crane master list") at first tab, the rest is not working,
ts
import { MatSort,Sort } from '@angular/material/sort';
@ViewChild(MatSort, { static: true }) sortCrane: MatSort;
@ViewChild(MatSort, { static: true }) sortLifeboat: MatSort;
preloadData() {
//fetch data from api
this.masterlistService.getCrane().subscribe(res => {
this.craneDataSource = new MatTableDataSource(res);
this.craneDataSource.sort = this.sortCrane;
});
this.masterlistService.getLifeboat().subscribe(res => {
this.lifeboatDataSource = new MatTableDataSource(res);
this.lifeboatDataSource.sort = this.sortLifeboat;
});
}
html
<mat-tab-group style='min-height:37rem;' (selectedTabChange)="onClickTab($event)">
<mat-tab label="Crane Masterlist">
<table mat-table [dataSource]="this.craneDataSource" style="margin-top: 3.5rem;" matSort (matSortChange)="announceSortChange($event)">
<ng-container matColumnDef="Region">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Region </th>
<td mat-cell *matCellDef="let item"> {{item.Region}} </td>
</ng-container>
//....etc
</table>
</mat-tab>
<mat-tab label="Lifeboat Masterlist">
<table mat-table [dataSource]="this.lifeboatDataSource" style="margin-top: 3.5rem;"
matSort (matSortChange)="announceSortChange($event)">
<ng-container matColumnDef="Region">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Region </th>
<td mat-cell *matCellDef="let item"> {{item.Region}} </td>
</ng-container>
//....etc
</table>
</mat-tab-group>
</mat-tab>
CodePudding user response:
Since you have more than one matSort in one file, using @ViewChild with just class name won't work. Use template reference variable instead.
<table #craneTable mat-table [dataSource]="this.craneDataSource" style="margin-top: 3.5rem;" matSort (matSortChange)="announceSortChange($event)"><!-- ... --></table>
<table #lifeboatTable mat-table [dataSource]="this.lifeboatDataSource" style="margin-top: 3.5rem;" matSort (matSortChange)="announceSortChange($event)"><!-- ... --></table>
@ViewChild("craneTable") sortCrane: MatSort;
@ViewChild("lifeboatTable") sortLifeboat: MatSort;
Alternatively, you may also use @ViewChildren
