angular - 使用 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 数组中重复。
解决方案
那是因为您在表格主体*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>
推荐阅读
- javascript - 退出搜索结果页面后获取上一个搜索结果
- android - Genymotion 3.0.1 安装后卡住且无法启动
- ios - 打开 iOS Swift 应用程序后立即在 Safari 中重定向
- python - 激活venv并检查python和django版本后的Django语法错误
- java - Spring:如何使用注释从同一个类中创建两个不同的 bean?
- c# - 将 json 文件作为参数传递给方法
- c++ - 使用基类之一的构造函数,而其他基类在多重继承中没有默认构造函数
- node.js - 隐蔽 Node.js 加密 HMAC 到 Go-lang HMAC 加密
- django - Django 与 Vue,检测表单验证错误
- r - 通过 R 中的 grep 进行自由文本分类