[英]Angular *ngFor loop through an array of arrays
我有一個數組,其中包含其他數組,像這樣:
array = [
["element A", "element B"],
["YES", "NO"]
]
我想使用ngFor在HTML表中遍歷此對象數組:
<table>
<thead>
<tr>
<th>#</th>
<th>COLUMN 1</th>
<th>COLUMN 2</th>
</tr>
</thead>
<tbody>
<template *ngFor="let row of csvContent; let in = index">
<th scope="row">{{in}}</th>
<template *ngFor="let c of row; let in = index">
<td>
{{c[0]}}
</td>
</template>
</template>
</tbody>
</table>
我想分別在COLUMN1和COLUMN2下面顯示每個內部數組列表:
COLUMN1 | COLUMN2
--------------------
element A | YES
element B | NO
我無法弄清楚如何正確使用* ngFor來列出數組數組(簡單的字符串列表)。 目前,它要么是一個空數組,要么是移位並弄亂了Table的演示文稿。
這是表格的外觀:
或由於元素A和B的值應低於第1列,而元素YES和NO則應低於COLUMN2,這是錯誤的表示:
您的數據不是數組中的數組; 這是兩個相連的陣列。 您需要這樣對待:
<tbody>
<tr *ngFor="let column of csvContent[0]; let in = index">
<td>
{{csvContent[0][in]}}
</td>
<td>
{{csvContent[1][in]}}
</td>
</tr>
</tbody>
這並不是組織數據的好方法,因為這些東西並不是真正相關的。 如果csvContent[0]
獲得一個新條目,但1沒有,該怎么辦? 現在,您的數據並不代表表格,我建議您在控制器中將其轉換為表格格式,然后進行打印。
嘗試這個:
<table>
<thead>
<tr>
<th>#</th>
<th>COLUMN 1</th>
<th>COLUMN 2</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of csvContent;let i = index;">
<td>{{i}}</td>
<td *ngFor="let c of row">
{{c}}
</td>
</tr>
</tbody>
</table>
我不確定您的數據是什么樣子,但是看起來這會有所幫助。 您實際上並不需要使用<template>
標記(無論如何,它們都已棄用了<ng-template>
標記。
另外,如果您仍然要在該索引處訪問數組,則無需進行索引跟蹤。
像這樣簡單地循環
<table>
<thead>
<tr>
<th>#</th>
<th>COLUMN 1</th>
<th>COLUMN 2</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of csvContent;let i = index;">
<td>{{i}}</td>
<td *ngFor="let c of row">{{c}}</td>
</tr>
</tbody>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.