Angular 2 ng For嵌套json

时间:2017-11-07 09:45:15

标签: angular ngfor

我是新的角度2.我能够获得Json文件。我能够获得一些部分json文件,但不能获取json文件中的数组。 例如,我想要在第二UL中的第一UL和IMU设备中可视化GPS设备。它们是阵列我在列表中获得了相同的IMU设备数据。

json文件

"config" : [
    {
        "id"      : "gps_device",
        "name"    : "GPS Device",
        "type"    : "String",
        "widget"  : "dropdown",
        "fields"  : [ "Disabled", "XSensIMU", "GenesysADMA"],
        "default" : "Disabled"
    },
    {
        "id"      : "imu_device",
        "name"    : "IMU Device",
        "type"    : "String",
        "widget"  : "dropdown",
        "fields"  : [ "Disabled1", "XSensIMU1", "GenesysADMA1"],
        "default" : "XSensIMU"
    }
]



//here I should get loop of GPS device array
<h1>Gps Device</h1>
<ul *ngFor="let drop of config[0]">
  <li *ngFor="let sub of drop.fields"> {{sub}}</li>
<ul>
//here array of IMU device

<h1>IMU Device</h1>
<ul *ngFOr="let drop1 of config[1]">
    <li *ngFOr="let sub1 of drop.fields"> {{sub1}}</li>
<ul>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

尝试使用此代码将您的设备分为两组:

<div *ngFor="let drop of config">
  <ng-container *ngIf="drop.id === 'imu_device'; else gpsBlock">
    <h1>IMU Device</h1>
    <ul>
      <li *ngFOr="let sub1 of drop.fields"> {{sub1}}</li>
    </ul>
  </ng-container>
  <ng-container #gpsBlock>
    <h1>Gps Device</h1>
    <ul>
      <li *ngFOr="let sub1 of drop.fields"> {{sub1}}</li>
    </ul>
  </ng-container>
</div>

循环配置,并在GPS或IMU div中有条件地显示设备

编辑: 或者你可以这样做:

  <ng-container *ngFor="let drop of configs">
    <h1>{{drop.name}}</h1>
    <ul>
      <li *ngFor="let field of drop.fields">{{field}}</li>
    </ul>
  </ng-container>

答案 1 :(得分:0)

您无法使用*ngFor

迭代对象

因为config[0]将等于

{
   "id"      : "gps_device",
   "name"    : "GPS Device",
   "type"    : "String",
   "widget"  : "dropdown",
   "fields"  : [ "Disabled", "XSensIMU", "GenesysADMA"],
   "default" : "Disabled"
}

哪个 iterable

迭代遍历config数组,这是一个数组

试试这个

<h1>IMU Device</h1>
<ul *ngFOr="let drop1 of config">
    <li *ngFOr="let sub1 of drop.fields"> {{sub1.name}}</li>
<ul>