Component (TS File) in my Angular Component-
const test_data1: any[] = [
{
name: 'John',
id: 1,
dateOfBirth: new Date(),
address: 'add1'
},
{
name: 'Sarah',
id: 2,
dateOfBirth: new Date(),
address: 'add2'
}
];
const test_data2: any[] = [
{
name: 'John',
id: 1,
department: 'dept 1,
manager: 'mgr_john'
},
{
name: 'Bob',
id: 2,
department: 'dept 2',
manager: 'mgr_bob'
}
];
public tabColumns: Array<any> = [];
public dataSource: Array<any> = [];
public displayedColumns: Array<any> = [];
ngOnInit() {
this.tabs = ['tab1', 'tab2']
this.tabColumns[0] = this.displayedColumns[0] = ['name', 'dateOfBirth1', 'address1'];
this.dataSource[0] = {};
this.dataSource[0].data = test_data;
this.tabColumns[1] = this.displayedColumns[1] = ['name', 'department', 'manager'];
this.dataSource[1] = {};
this.dataSource[1].data = test_data2;
...
}
In this sample I have 2 tables. But, in the app the number of tabs and the table content in the tab is dynamic. I want to display each of the table under its own tab (with a common filter bar at the top, which filters any mathching table data). I got this working with a single table (without loops), but when I updated to use an array, UI is not showing the table data.
HTML code -
<div>
<mat-form-field style="width:100% !important">
<input matInput type="text" (keyup)="doFilter($event.target.value)" placeholder="Search">
</mat-form-field>
</div>
<mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab.name">
<table mat-table [dataSource]="dataSource[index]" matSort>
<ng-container [matColumnDef]="col" *ngFor="let col of displayedColumns[index]">
<th mat-header-cell *matHeaderCellDef> {{col | uppercase}} </th>
<td mat-cell *matCellDef="let element"> {{element[col]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns[index]"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns[index];"></tr>
</table>
</mat-tab>
Component (TS file) code for sorting and searching -
@ViewChild(MatSort, { static: false }) sort: MatSort;
ngAfterViewInit(): void {
this.dataSource.foreach(source => {
this.dataSource.sort = this.sort;
});
}
public doFilter = (value: string) => {
this.dataSource.foreach(source => {
this.dataSource.filter = value.trim();
});
}