java - Angular *NgFor 将数组中的字符串迭代到表 TD 标记
问题描述
我创建了一个从后端检索 JSON 数据的角度页面。
Json 输出的格式如下
fields
0 "count"
1 "Date"
2 "Status"
rows
0 "["2","2019-11-21","Operate"]"
1 "["3","2019-12-12","Maintain"]"
________________________________________________
{
"fields":
["count","Date","Status"],
"rows":
[
"["2","2019-11-21","Operate"]",
"["3","2019-12-12","Maintain"]"
],
"id":
0
}
我想在前端创建一个表格,使用字段中的值作为标题,将行中的值作为单元格。例如
_____________________________
| count | Date | Status |
|---------------------------|
| 2 |2019-11-21| Operate|
| 3 |2019-12-12|Maintain|
-----------------------------
但是,当调用数据时,我得到了这些结果
| count | Date | Status |
|-------------------------------------------------|
|["2","2019-11-21","Operate"] | | |
|["3","2019-12-12","Maintain"]| | |
---------------------------------------------------
我的表格html代码如下
<table class="table table-borderless table-striped table-hover" *ngIf="appDetail?.fields">
<thead>
<th *ngFor="let field of appDetail.fields" class="table-header">{{field}}</th>
</thead>
<tbody>
<tr *ngFor="let row of appDetail.rows">
<td *ngFor="let item of row">{{item}}</td>
</tr>
</tbody>
</table>
我的模特
export class AppDetail {
public fields: string[];
public rows: string[][];
}
我的组件
public getSealData() {
this.sealidService.getSplunkData(this.idValue).subscribe(data => {
this.appDetail = data as AppDetail;
console.log(data.fields);
console.log(data.rows);
})
}
编辑 现在我在之间进行迭代,我在控制台中收到以下错误消息
ERROR Error: Cannot find a differ supporting object of type String
我假设这与我的模型有关?
编辑 原来我没有得到一个数组数组,而是一个字符串数组。看起来正在进行一些解码,但实际的 JSON 看起来更像这样
"fields":
["count","Date","Status"],
"rows":
["[\"2\",\"2019-11-21\",\"Operate\"]", "[\"3\",\"2019-12-12\",\"Maintain\"]"],
所以我得到的错误是由于字符串值不可迭代。Console.log 输出 console.log(data.rows)
0: "["2","2019-11-21","Operate"]"
1: "["2","2019-12-02","Maintain"]"
已解决 - 我将不得不与后端数据的所有者合作,以获得适用于 Saurabh 答案的正确格式。
解决方案
你可以这样做:迭代行,行元素本身是数组,而不是再次迭代那些要渲染的元素td
<tbody>
<tr *ngFor="let row of appDetail.rows">
<td *ngFor="let item of row">{{item}}</td>
</tr>
</tbody>
推荐阅读
- ruby-on-rails - Rspec 控制器规范不会因缺少模板而失败
- c# - Vs.Net C# Azure 文件存储无法为现有文件共享添加文件
- xamarin - 如何为大写 Ctlr+A 和小写 Ctlr+a 的控制字符创建 KeyEvent
- java - 从其他活动通知片段
- material-ui - 如何更改 Material UI 工具栏的高度?
- java - JPA Entity 是否存储对 Entity Manager 的引用?
- laravel - 从数据透视表字段创建关系
- c# - 将页面可见设置为 true 失败
- r - R中是否有可能用循环填充直方图?
- r - 正确的函数是 R 用于从 data.frame 中的向量中查找元素的行索引吗?