html - 使用 *ngFor 將一個陣列內的陣列填充到表格中
我需要一個流行的表格來比較兩個產品。我的 JSON 模型包含一個陣列在另一個陣列裡。就這樣。
products: [
{
nome: 'Product Basic',
preco: 9.90,
categoria: 1,
caracteristicas: [
'1 basic',
'2 basic',
'3 basic',
'4 basic',
'5 basic',
'6 basic]
},
{
nome: 'Product Plus',
preco: 14.90,
categoria: 1,
caracteristicas: [
'1 Plus',
'2 Plus',
'3 Plus',
'4 Plus',
'5 Plus',
'6 Plus']
}
]
我正在這樣創建表格
<tr *ngFor="let columnCaracteristica of tableComparative.columns">
<td>{{columnCaracteristica}}</td>
<ng-container *ngFor="let produto of tableComparative.produtos">
<td *ngFor="let caracteristica of produto.caracteristicas">{{caracteristica}}</td>
</ng-container>
</tr>
要比較的特徵
columns: ['Agencia', 'Encandor', 'Roubo', 'Vale presente', 'Raios', 'Fogo'],
結果
預期
答案#1
你可以依照以下範本來做
<table *ngIf="products?.length">
<tr *ngFor="let characteristic of products[0].caracteristicas; let i = index">
<td>
{{ columns[i]}}
</td>
<td *ngFor="let product of products">
{{ product.caracteristicas[i] }}
</td>
</tr>
</table>
Ng-run 範例
此外,如果你願意,你還可以添加頂部標題來顯示產品名稱
<thead>
<tr>
<th></th>
<th *ngFor="let product of products">
{{ product.name }}
</th>
</tr>
</thead>
Ng-run 範例


