我正在尝试动态开发mat-table,其中已根据下拉选择动态分配了DataSource。这里的问题是我无法迭代动态数组来设置列标题。这里的问题是我从下拉列表中选择值,并从不知道如何继续的dataSourceArr映射数据。请帮助我。 使用的示例JSON
dataSourceArr = [{
BookID: 56353,
BookAuthor: 'Sir Alex Ferguson',
BookTitle: 'Leading'
},
{
BookID: 73638,
BookAuthor: 'Eric Smith',
BookTitle: 'How Google Works'
},
{
BookID: 37364,
BookAuthor: 'William Shakespeare',
BookTitle: 'The Merchant of Venice'
}];
<mat-form-field>
<mat-label>Books</mat-label>
<mat-select [formControl]="bookCategories" multiple (selectionChange)="selectedColumns($event.value)">
<mat-option *ngFor="let list of selectedList" [value]="list">
{{list}}</mat-option>
</mat-select>
</mat-form-field>
<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let disCol of tableDataSource ; let colIndex = index" matColumnDef="{{disCol}}">
{{disCol}}
<mat-header-cell *matHeaderCellDef>{{disCol}}</mat-header-cell>
<mat-cell *matCellDef="let element "> {{element[disCol]}}
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="tableDataSource"></mat-header-row>
<mat-row *matRowDef="let row; columns: tableDataSource;"></mat-row>
</mat-table>
To assign only the keys to dropdown options from the data fetched dynamically .
this.dataSourceArr.forEach(val => {
this.selectedList = Object.keys(val);
});
// Mapping datasource based on the dropdown selection i.e bookid,bookauthor,bookTitle
selectedColumns(columns) {
this.tableDataSource = [];
this.dataSourceArr.map((obj) => {
const result = columns.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
this.tableDataSource.push(result);
})
}
根据下拉列表映射selectedColumns函数中的dataSource值后的结果。
[{
"BookAuthor": "Sir Alex Ferguson",
"BookTitle": "Leading"
},
{
"BookAuthor": "Eric Smith",
"BookTitle": "How Google Works"
},
{
"BookAuthor": "William Shakespeare",
"BookTitle": "The Merchant of Venice"
}]
我需要将数据源动态分配给mat-table,必须基于下拉选择设置列,其中键和值也将是来自服务器的动态数据。如果在下拉列表中选择BookAuthor和BookTitle,则只需要显示BookAuthor,BookTitle作为标题,并在表中显示其值。