Angular *ngFor 遍历数组数组

Angular *ngFor loop through an array of arrays

我有一个包含其他数组的数组:

array = [
           ["element A", "element B"],
           ["YES", "NO"]
        ]

我想使用 ngFor:

在 HTML table 中遍历这个对象数组
   <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 演示文稿。

这是 Table:

的样子

或者这个错误的呈现,因为元素 A 和 B 应该在 COLUMN 1 下面,YES,NO 应该在 COLUMN2 下面:

试试这个:

<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>

您的数据不是数组中的数组;它是两个相连的阵列。您需要这样对待它:

   <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,我建议您在控制器中将其转换为 tabluar,然后打印。