我正在尝试从包含数组的 Json 动态创建 html 表。我遇到的问题是尝试从子数组创建<td>
时。下面是我试图完成的示例。
我应该使用<ng-container *ngFor="let m of l.dArray">
吗?
myArray = [ {
"a": "01",
"b": "01",
"c": "03",
"dArray": [
{
"d-1": 1,
"d-2": 2,
"d-3": "string1"
},
{
"d-1": 2,
"d-2": 1,
"d-3": "string2"
},
{
"d-1": 3,
"d-2": 4,
"d-3": "string3"
}
]
}
]
模板:
<table>
<thead>
<tr><th>A</th></tr>
<tr><th>B</th></tr>
<tr><th>C</th></tr>
<tr><th>D-1</th></tr>
<tr><th>D-2</th></tr>
<tr><th>D-3</th></tr>
</thead>
<tbody>
<tr *ngFor="let l of myArray">
<td>{{l.a}}</td>
<td>{{l.b}}</td>
<td>{{l.c}}</td>
<ng-container *ngFor="let m of l.dArray">
<td>
<div *ngIf="m.d-1 === 1; else my1Else">
{{ m.d-3 }}%
</div>
<ng-template #my1Else>
N/A
</ng-template>
</td>
<td>
<div *ngIf="m.d-1 === 2; else my2Else">
{{ m.d-3 }}%
</div>
<ng-template #my2Else>
N/A
</ng-template>
</td>
<td>
<div *ngIf="m.d-1 === 1; else my3Else">
{{ m.d-3 }}%
</div>
<ng-template #my3Else>
N/A
</ng-template>
</td>
</ng-container>
</tr>
</tbody>
</table>
预期成果:
----------------------------
A | B | C | D-1 | D-2 | D-3
01 | 01| 03 | string1 | string2 | string3
actual outcome:
----------------------------
A | B | C
我做了几件事:
- 数组的名称是 dArray 分别是"d-1"、"d-2"、"d-3"...名称中包含运算符;我将它们重命名为D1,D2和D3 。
- 您希望在"D-1"列中仅显示一个值,因此我们执行
*ngIf='i==0'
以确保我们评估此表列"D-1"的dArray
的第一行 - 我们必须使用嵌套的 if 和 else,以便只打印一个有效值,否则我们得到一个 N/A
相关网页:
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D-1</th>
<th>D-2</th>
<th>D-3</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let l of myArray">
<td>{{l.a}}</td>
<td>{{l.b}}</td>
<td>{{l.c}}</td>
<ng-container *ngFor="let m of l.dArray; let i=index">
<td *ngIf='i===0'>
<div *ngIf="m.d1 === 1; else my1Else1">
{{ m.d3 }}%
</div>
<ng-template #my1Else1>
<div *ngIf="m.d1 === 2; else my2Else2">
{{ m.d3 }}%
</div>
<ng-template #my2Else2>
<div *ngIf="m.d1 === 3; else my3Else3">
{{ m.d3 }}%
</div>
<ng-template #my3Else3>
N/A
</ng-template>
</ng-template>
</ng-template>
</td>
<td *ngIf='i===1'>
<div *ngIf="m.d1 === 1; else my1Else1">
{{ m.d3 }}%
</div>
<ng-template #my1Else1>
<div *ngIf="m.d1 === 2; else my2Else2">
{{ m.d3 }}%
</div>
<ng-template #my2Else2>
<div *ngIf="m.d1 === 3; else my3Else3">
{{ m.d3 }}%
</div>
<ng-template #my3Else3>
N/A
</ng-template>
</ng-template>
</ng-template>
</td>
<td *ngIf='i===2'>
<div *ngIf="m.d1 === 1; else my1Else1">
{{ m.d3 }}%
</div>
<ng-template #my1Else1>
<div *ngIf="m.d1 === 2; else my2Else2">
{{ m.d3 }}%
</div>
<ng-template #my2Else2>
<div *ngIf="m.d1 === 3; else my3Else3">
{{ m.d3 }}%
</div>
<ng-template #my3Else3>
N/A
</ng-template>
</ng-template>
</ng-template>
</td>
</ng-container>
</tr>
</tbody>
</table>
您可以在此处查看工作堆栈闪电战