我正在尝试将我的对象之一映射到mat-table
。
来自Web API的输入对象如下:
[
{
"inventoryId": 1004,
"inventoryName": "Red Shirt Material",
"dateReport": [
{
"date": "2019-03-04T19:15:16.828",
"quantity": 109.9
},
{
"date": "2019-03-09T10:36:12.198",
"quantity": 26.6
}
]
},
{
"inventoryId": 1003,
"inventoryName": "Blue Pant Material",
"dateReport": [
{
"date": "2019-03-04T19:15:16.828",
"quantity": 64.4
},
{
"date": "2019-03-09T10:36:12.198",
"quantity": 8
}
]
}
]
HTML代码
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="sn">
<th mat-header-cell *matHeaderCellDef mat-sort-header>S.No.</th>
<td mat-cell *matCellDef="let row; let i = index">{{ i + 1 }}</td>
</ng-container>
<ng-container matColumnDef="InventoryName">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let row">{{ row.inventoryName }}</td>
</ng-container>
<ng-template *ngFor="let row;let item of row?.dateReport" >
<ng-container matColumnDef={{ item.date | date }}>
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ item.date | date }}</th>
<td mat-cell *matCellDef="let srow">{{ item.quantity}}</td>
</ng-container>
</ng-template>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
角度模型:
export class ShoppingListModel {
inventoryId: number;
inventoryName: string;
dateReport: ShoppingListDateModel[] = [];
}
export class ShoppingListDateModel {
date: Date;
quantity: number;
}
角度代码:
export class ShoppingListComponent implements OnInit {
dataSource: MatTableDataSource<ShoppingListModel>;
displayedColumns = [
'InventoryName',
'Quantity',
'InStock',
// 'Diff',
'UnitId'
];
constructor(
private reportService: ReportService
) {
}
Search() {
this.rService.getShoppingListReport(this.Params).subscribe(
data => {
this.dataSource = new MatTableDataSource(data);
});
}
预期的输出:dateReport包含用作表中列名称的日期。下方的结构“ n”表示webapi可能返回两个以上的ShoppingListDateModel,在这种情况下,应为每个日期添加该列
________________________________________________________________
| S.No | Name | 04-03-2019 | 09-03-2019 | .....n |
|______________________________________________________________|
| | | | | |
| 1 | Red Shirt Material | 109.9 | 26.6 | .....n |
| | | | | |
| 2 | Blue Pant Material | 64.4 | 8 | .....n |
|______________________________________________________________|
问题:
无法基于dateRecord生成列。 UI仅呈现前两列。
我是Angular的新手。如果执行错误,请通知我,我可以根据输入内容进行修改。
答案 0 :(得分:1)
这可能是由于dataSource
在组件的初始化中未定义。您刚刚为其指定了一种类型。因此,一种方法是进行
dataSource = new ShoppingListModel(... default data)
那么它将不会是不确定的。
另一种方法是添加*ngFor="let row;let item of row?.dateReport"
,如果?
未定义,则row
不会引发错误。