Angular 2 ngFor for nested json [duplicate]

試著忘記壹切 提交于 2020-01-07 09:53:44

问题


I am new angular 2. I am able to get Json file. I am able to get some part json file but not the array inside json file. For example I want to visualise GPS device in First UL and IMU device in second UL. SInce they are array I am getting same data of IMU device in bOTH the lists.

json file

"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>

回答1:


Try this code to separate your devices into 2 groups :

<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>

You loop on config, and conditionnally display device in GPS or IMU divs

EDIT : Or you can doing it this way :

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


来源:https://stackoverflow.com/questions/47154554/angular-2-ngfor-for-nested-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!