To display columns and headings using *ngFor, you can use the Angular *ngFor
directive; for the actual values, write the corresponding code in the TS file.
Here is the relevant HTML code snippet:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor='let disCol of displayedColumns; let i = index'>
<ng-container matColumnDef="{{disCol}}">
<th mat-header-cell *matHeaderCellDef> {{disCol}} </th>
<td mat-cell *matCellDef="let element"> {{returnVal(element, disCol)}} </td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
And here is the relevant TS code snippet:
import {Component} from '@angular/core';
export interface PeriodicElement {
name: string;
position: number;
weight: number;
symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
// Data objects
];
@Component({
selector: 'table-basic-example',
styleUrls: ['table-basic-example.css'],
templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = ELEMENT_DATA;
// Function to return values based on column type
returnVal(element, dispCol){
switch(dispCol){
case 'position': return element.position;
case 'name': return element.name;
case 'weight': return element.weight;
case 'symbol': return element.symbol;
}
}
}
You can see a complete working example on StackBlitz.