I am faced with a challenge involving multiple dynamically created Angular tables, each containing the same columns but different data. The issue at hand is sorting the columns in each table separately. At present, I have two tables set up. On clicking the column header arrow on the first table, it sorts correctly while doing the same on the second table yields no result.
Below is the pertinent HTML code snippet:
<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's the relevant TypeScript snippet:
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];
};
}
Is there anyone who can identify what might be causing my issue?