ngFor 超过 json 生成 table

ngFor over json to generate a table

我有 json 数组如下,

[ { "AccountName": "test1", "Amount": "-28.11" }, { "AccountName": "test2", "Amount": "400" }, { "AccountName": "test3", "Amount": "-500" } ]

我需要生成一个table如下,

test1 | test2 | test3
---------------------
-28.11| 400   | 500

这是我试过的

 <table>
      <thead>
        <tr>
          <td *ngFor=" let key of accountList">
            {{key.AccountName}}
          </td>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor=" let res of accountList">
          {{res.Amount}}
        </tr>
      </tbody>
    </table>

这会生成 3 个水平行,我希望在一行中显示相应的标题。

您的第二行正在生成更多行(在 tr 上循环),而不是列。添加另一个 td 级别并在其上循环:

<table>
  <thead>
    <tr>
      <td *ngFor=" let key of accountList">
        {{key.AccountName}}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td *ngFor=" let res of accountList">
        {{res.Amount}}
      </td>
    </tr>
  </tbody>
</table>

笨蛋:http://plnkr.co/edit/MldBaGTVGEPi7apIT0V0?p=preview

<tr>  <td *ngFor=" let res of accountList"> {{res.Amount}} </td></tr>

你可以用这个,

<table>
  <td *ngFor=" let key of accountList">
    <tr>
      <th> {{ key.AccountName }} </th>
    </tr>
    <tr>
      <td> {{ key.Amount }} </td>
   </tr>
  </td>
</table>

如果您只希望模板中有一个 ngFor。 (确认它在本地工作)。此逻辑基本上根据数组长度向右侧附加越来越多的列(header 和值在 2 行内)。希望对你有帮助。