Reputation: 368
I have a normal Material 2 DataTable, and I want to custom the table header by object
For Example:
<mat-form-field style="width:100%">
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="{{item}}" *ngFor="let item of old_title_list">
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{item}} </th>
<td mat-cell *matCellDef="let row"> {{row[item]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;">
</tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" [pageSize]="25" showFirstLastButtons></mat-paginator>
</div>
It successfully display the table, however the th
is just presenting the item name defined in data_list
object.
So I expect I should change the code to something like below:
<ng-container matColumnDef="{{item.data}}" *ngFor="let item of new_title_list">
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{item.title}} </th>
<td mat-cell *matCellDef="let row"> {{ row[item.data] }} </td>
</ng-container>
I expect it can get the header value by key but it doesn't. What should I do ?
Sample data:
var old_title_list = ['aaaaa', '1111', '2222', '3333'];
var data_list: [{
aaaaa: 'World',
'1111': 'this is 1111',
'2222': 'this is 2222',
'3333': 'this is 3333',
},{
aaaaa: 'World',
'1111': 'this is 1111',
'2222': 'this is 2222',
'3333': 'this is 3333',
},{
aaaaa: 'World',
'1111': 'this is 1111',
'2222': 'this is 2222',
'3333': 'this is 3333',
}];
var new_title_list = [
{data: 'aaaaa', title: 'Hello'},
{data: '1111', title: '1'},
{data: '2222', title: '2'},
{data: '3333', title: '3'},
];
Upvotes: 0
Views: 2318
Reputation: 442
You item is object. You must get keys of object by item.keys(), after you can use array of keys to show column name. You can try something like this:
<ng-container matColumnDef="{{item.keys()[i]}}" *ngFor="let item of data_list; let i = index">
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{item.keys()[i]}} </th>
<td mat-cell *matCellDef="let row"> {{ (row[item.data] }} </td>
</ng-container>
if you want use titles from title_list array you can use this code:
<ng-container matColumnDef="{{title_list[i].title}}" *ngFor="let item of data_list; let i = index">
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{title_list[i].title}} </th>
<td mat-cell *matCellDef="let row"> {{ (row[item.data] }} </td>
</ng-container>
Upvotes: 1