I have multiple dynamically created Angular tables, each displaying the same columns but with different data. I need to sort the columns in each table separately. I currently have two tables. When I click on the column header arrow on the first one, it sorts correctly. Clicking on the same column in the second table does nothing.
Here is the relevant html:
<div appMaterialElevation *ngFor="let item of tables; let i = index">
<table
mat-table
[dataSource]="item.dataSource"
multiTemplateDataRows
matSort
matSortActive="configName"
matSortDirection="asc"
>
<ng-container matColumnDef="configName">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Table Name</th>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
</div>
Here is the relevant TS:
import { Component, ViewChild, ViewChildren, QueryList, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
export class Row {
configName: string;
}
export class FormatData {
formatName: string;
dataSource: MatTableDataSource<Row>;
selection: SelectionModel<Row>;
}
export class ConfigureFormatsComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChildren(MatPaginator) paginators = new QueryList<MatPaginator>();
@ViewChildren(MatSort) sorts = new QueryList<MatSort>();
tables: FormatData[];
displayedColumns: string[] = ['configName'];
getconfigformats() {
this.tables = [] as FormatData[];
this.myService.getMyData()
.subscribe((configList: MyConfigs[]) => {
let table = new FormatData();
let configNamesList = [] as Row[];
configList.forEach(config => {
let row = new Row();
row.configName = config.configName;
configNamesList.push(row);
});
table.dataSource = new MatTableDataSource<Row>(configNamesList);
table.selection = new SelectionModel<Row>(true, []);
this.tables.push(table);
this.ngAfterViewInit();
}
});
}
ngAfterViewInit() {
for (let i=0; i<this.tables.length; i++) {
let table = this.tables[i];
table.dataSource.sort = this.sorts.toArray()[i];
table.dataSource.paginator = this.paginators.toArray()[i];
};
}
Can anybody see my mistake?