如何在angular 2 中动态设置table 航向?

How to set table heading dynamically in angular 2?

我正在获取 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
      }
      }]

我想将所有键设置为 table 标题,将数据设置为 table 行。我参考了以下链接

Link 2:

任何plunker都会对我很有帮助。

关键的解决方案是将对象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 对象转换为数组。

这是一个working plunkr.

正在阅读以下部分:

    <tr *ngFor=" let res of ResultData">
      <td *ngFor=" let key of keys">
        {{res[key]}}
      </td>
    </tr>

ResultData 是一个项目数组。我们将为每个项目创建一个 table 行,并显示每个项目的内容。这就是为什么我们为数组 ResultData.

中的每个项目 res 重复 <tr>

然后,对于 ResultData 中的每个项目 res 我们将迭代我们之前在 ts 代码中准备的 keys 的数组。对于 keys 中的每个项目 key,我们会将项目的值显示为 {{res[key]}}