首页 > 解决方案 > 使用 Angular NgFor 用 JSON 数组中的数据填充 html 数据表

问题描述

我正在将大量的 excel 电子表格转换为 json,然后构建一个工具来格式化数据并将其用于分析。

在上传过程中,我向用户展示了他们所有数据的视图。我在格式化表格时遇到了一些麻烦,我希望这里有人可以帮助解释这个问题:

在 html 中使用标准数据表时,我可以在硬编码时轻松获得我想要的结果:

<div style="margin-bottom: 10px">
    <table class="table table-responsive table-condensed">
      <tr>
        <th style="color: black" *ngFor="let label of lineChartLabels">{{label}}</th>
      </tr>
      <tr *ngFor="let d of XLSData">
        <td>This is in Column 1</td>
        <td>And this is in Column 2</td> 
      </tr>
    </table>
  </div>

我得到了这个: 正确表 但是当用 NgFor 填充行时,我得到每列重复的数据:

<div style="margin-bottom: 10px">
    <table class="table table-responsive table-condensed">
      <tr>
        <th style="color: black" *ngFor="let label of lineChartLabels">{{label}}</th>
      </tr>
      <tr *ngFor="let d of XLSData">
        <td style="color: black" *ngFor="let label of lineChartLabels">Time: {{d.Time | json}}</td>
        <td style="color: black" *ngFor="let label of lineChartLabels">Empty: {{d.__EMPTY | json}}</td>
      </tr>
    </table>
  </div>

我明白了: 错误表

我不明白为什么循环会用相同的数据填充每一列可用的数据,因为数据不会在 JSON 数组中重复。

标签: angulartypescripthtml-table

解决方案


那是因为您在表格主体*ngFor内的列上执行了两个操作。tr

如果您的数据始终具有相同的列,只需对其*ngFor进行硬编码(列不需要):

<div style="margin-bottom: 10px">
    <table class="table table-responsive table-condensed">
      <tr>
        <th style="color: black">Time</th>
        <th style="color: black">__EMPTY</th>
      </tr>
      <tr *ngFor="let d of XLSData">
        <td style="color: black">Time: {{ d.Time | json }}</td>
        <td style="color: black">Empty: {{ d.__EMPTY | json }}</td>
      </tr>
    </table>
</div>

如果您的列是动态的,那么您需要*ngFor在列上:

<div style="margin-bottom: 10px">
    <table class="table table-responsive table-condensed">
      <tr>
        <th style="color: black" *ngFor="let label of lineChartLabels">
          {{ label }}
        </th>
      </tr>
      <tr *ngFor="let d of XLSData">
        <td style="color: black" *ngFor="let label of lineChartLabels">
          <!-- Note that I'm assuming here that your label is the same of your field name on `d`. If is not, you will need to better structure your code -->
          {{ d[label] | json }}
        </td>
    </table>
</div>

推荐阅读