I'm trying to have a dynamic table set up as follows:
Typescript
export class TestTableComponent implements OnInit {
data = DATA1;
displayedColumns = Object.keys(this.data[0]);
}
const DATA1 = [
{iid: 11131, shortname: 'AOCS', actval: ""},
{iid: 225124, shortname: '|--El1', actval: ""},
{iid: 35412, shortname: '|--|--El1.2', actval: "1"},
{iid: 456512, shortname: '|--|--El2.1', actval: "2"},
{iid: 55512, shortname: '|--El2', actval: ""},
{iid: 62111, shortname: '|--|--El2.1', actval: "3"},
{iid: 72334, shortname: '|--|--El2.2', actval: "4"},
];
Html:
<table mat-table [dataSource]="data" class="table">
<ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let emp"> {{emp[column]}} </td>
</ng-container>
<ng-container>
<tr mat-header-row *matHeaderRowDef="['iid']"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</ng-container>
</table>
While the table displays, it only shows one header for some reason:
What am I doing wrong?
Here is a correct syntax
<table mat-table [dataSource]="data" class="table">
<ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let emp"> {{emp[column]}} </td>
</ng-container>
<!-- No need for wrapping in ng-container -->
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <!-- You have added only ['iid'] to display-->
<!-- What columns to display and in what order will be decided based on the above array -->
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
The problem showing because this line of code:
<tr mat-header-row *matHeaderRowDef="['iid']"></tr>
You are only setting the first key of your data: DATA1
as the column to be displayed.
Here is the solution :
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.