【发布时间】:2018-02-09 12:43:01
【问题描述】:
我正在使用 Angular4 从 API 获取数据并使用 *ngFor 呈现数据表的项目。因为我还有更多结构相同的 aip,所以我想使用 (key, value) 对来显示它们。在 AngularJS 中,我正确地呈现了这样的表格:
<!--This is Good in AngularJS-->
<table>
<thead>
<tr>
<th ng-repeat="(key, value) in data.items[0]"> {{key}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat ="data in data.items >
<td ng-repeat="(key,value) in data">{{ value }}</td>
</tr>
</tbody>
</table>
但是,表格在 Angular4 中显示不正确。来自 API 的原始 json 数据显示如下:
{
items: [
{
status: "Sold - Payment Received",
count: 30,
loans: 8,
dl_loans: 8,
avg_available: 149.5,
min: 28,
max: 346,
principal: 13452.37,
closed: 0,
chrg_of_balance: 0,
final_balance: 0
},
{
status: "At Auction - Awaiting Info",
count: 4,
loans: 4,
dl_loans: 4,
avg_available: 70.45,
min: 36,
max: 102,
principal: 11727.8,
closed: 0,
chrg_of_balance: 0,
final_balance: 0
},
...
}
这是我的 app.component.ts:
ngOnInit(): void {
this.dataService.getData().subscribe(
(data) => {
this.data = data.items;
this.titles = data.items[0];
}
);
}
我为过滤键和值创建了一个 pip.ts:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
在 Angular4 HTML 中:
<!--This is Bad in Angular4-->
<table>
<thead align="center">
<tr>
<th *ngFor = "let item of titles | keys">
{{item.key}}
</th>
</tr>
</thead>
<tbody>
<tr>
<td *ngFor = "let item of data | keys ">
{{item.value | json }}
</td>
</tr>
</tbody>
</table>
但是 UI 中的 thead 显示正常,但 tbody 部分显示包括整个对象(部分):
status
---------------------------------------
{
status: "Sold - Payment Received",
count: 30,
loans: 8,
dl_loans: 8,
avg_available: 149.5,
min: 28,
max: 346,
principal: 13452.37,
closed: 0,
chrg_of_balance: 0,
final_balance: 0
}
--------------------------------------
任何人都知道如何正确呈现此表?提前谢谢你!
【问题讨论】:
-
您不能循环
title,因为标题被放置到数据中的单个项目this.titles = data.items[0];可能正在更改为数据将起作用 -
stackoverflow.com/a/45880284/7491209 这可能会有所帮助
标签: angular angularjs-ng-repeat ngfor