Angular *ngFor loop through an array of arrays

坚强是说给别人听的谎言 提交于 2020-06-17 03:34:39

问题


I have an array which contains other arrays inside like that:

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

And I want to loop through this array of object in an HTML table using ngFor:

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

I want to display each inner array list below COLUMN1 and COLUMN2 respectively:

 COLUMN1   | COLUMN2
 --------------------
 element A | YES
 element B | NO

I can't figure it out how to use *ngFor properly in order to list an array of arrays (Simple list of strings). At the moment, it's either an empty array or a shifted & messed up Table presentation.

This is how looks the Table:

Or this wrong presentation because Element A and B should be below COLUMN 1 and YES, NO should be below COLUMN2:


回答1:


Your data is not arrays in arrays; it's two connected arrays. You need to treat it as such:

   <tbody>
     <tr *ngFor="let column of csvContent[0]; let in = index">
       <td>
         {{csvContent[0][in]}}
       </td>
       <td>
         {{csvContent[1][in]}}
       </td>
     </tr>
   </tbody>

This is not really a good way of organizing your data, as stuff is not really related. What if csvContent[0] gets a new entry, but 1 doesn't? Right now, your data doesn't represent a table, and I'd recommend transforming it in your controller to be tabluar, and then printing.




回答2:


Try this:

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

I wasn't sure how your data looked like, but seems like this would help. You don't really need to use <template> tags (they're deprecated anyway in favor of <ng-template> tags.

Also, no need for index tracking if you're gonna access the array at that index anyway.




回答3:


Simply loop like this

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


来源:https://stackoverflow.com/questions/48150500/angular-ngfor-loop-through-an-array-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!