Angular 2 ngFor for nested json [duplicate]

2019-09-26 23:54发布

问题:

This question already has an answer here:

  • How to do ngFor loop on nested json object? 4 answers

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>


标签: angular ngfor