我正在获取JSON数据,我正在将JSON数据存储在我的属性中。
this.ResultData_search=data.json().extras.ResultData
this.ResultData=[
{
"First_name": "xx",
"Email": "xxxx",
"Phone": "xxx",
"countryCode": "+91",
"order_datetime": "xxx",
"status": 11,
"DeviceType": 3,
"orderId": "59081a04c9ff6852a49dd32a",
"orderseqId": "E00002347",
"orderType": 1,
"CustomerID": "xx",
"pickAddress": "xx",
"dropAddress": "xx",
"pickLatitude": 17.4369414,
"dropLatitude": 17.43673,
"dropLongitude": 78.36710900000003,
"paymentType": 2,
"itemDescription": "",
"receiverName": "uday",
"receiverPhone": "xx",
"itemName": "sanjay",
"deliverycharge": "199",
"bookingType": 1
}
}]
我想将所有键设置为表标题,将数据设置为表行。我参考了以下链接https://stackoverflow.com/questions/40713580/angular2-table-with-dynamic-rows-and-columns
链接2:Dynamically loading columns and data in to table in Angular 2
任何吸毒者对我都非常有帮助。
答案 0 :(得分:5)
关键解决方案是将对象ResultData
转换为键数组。然后你可以轻松地迭代它。您可以使用Object.keys(this.ResultData)
获取对象的键。
component.ts
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<table>
<thead>
<tr>
<td *ngFor=" let key of keys">
{{key}}
</td>
</tr>
</thead>
<tbody>
<tr *ngFor=" let res of ResultData">
<td *ngFor=" let key of keys">
{{res[key]}}
</td>
</tr>
</tbody>
</table>
`,
})
export class App {
name:string;
ResultData=[
{
"First_name": "xx",
"Email": "xxxx",
"Phone": "xxx",
"countryCode": "+91",
"order_datetime": "xxx",
"status": 11,
"DeviceType": 3,
"orderId": "59081a04c9ff6852a49dd32a",
"orderseqId": "E00002347",
"orderType": 1,
"CustomerID": "xx",
"pickAddress": "xx",
"dropAddress": "xx",
"pickLatitude": 17.4369414,
"dropLatitude": 17.43673,
"dropLongitude": 78.36710900000003,
"paymentType": 2,
"itemDescription": "",
"receiverName": "uday",
"receiverPhone": "xx",
"itemName": "sanjay",
"deliverycharge": "199",
"bookingType": 1
}
]
constructor() {
}
keys: string[]=[];
ngOnInit() {
this.keys= Object.keys(this.ResultData[0])
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
这个link有另一种使用管道将JSON对象转换为数组的方法。
退出以下部分:
<tr *ngFor=" let res of ResultData">
<td *ngFor=" let key of keys">
{{res[key]}}
</td>
</tr>
ResultData
是一系列项目。对于每个项目,我们将创建一个表格行,我们将显示每个项目的内容。这就是为什么我们对数组<tr>
中的每个项res
重复ResultData
。
然后,对于res
中的每个项ResultData
,我们将遍历我们之前在ts代码中准备的keys
数组。对于key
中的每个项目keys
,我们会将项目的值显示为{{res[key]}}
。