Angular2 嵌套 *ngFor

Angular2 nested *ngFor

我使用一个数组来存储组对象列表和一个灯光对象列表数组。 我想显示 html 中的第一组以及该组的所有连接灯。之后就是下一组和相关的灯等等....

<div>
  <ul>
    <li *ngFor="let group of hueGroups">
      {{group.name}}
      <li *ngFor="let light of hueLights; let i = index">
      {{hueLights[group.lights[i]].name}}
    </li>
  </ul>
</div>



export class AppComponent implements OnInit {
  hueGroups:any[];
  hueLights:any[];

  constructor(){
    this.hueGroups = [];
    this.hueLights = [];
  }

  listAllGroups(){
   for(var g in MyHue.Groups){ //MyHue.Groups returen an array with objects
    console.log(g);
    console.log(MyHue.Groups[g].name);
    for(var id:number = 0; id < MyHue.Groups[g].lights.length; id++){
      console.log("LightID:" + MyHue.Lights[MyHue.Groups[g].lights[id]].name); // Returns the name of the Lights
    }
    this.hueGroups.push(MyHue.Groups[g]);
  }

  listAllLights(){
   for(var l in MyHue.Lights){ //MyHue.Lights returns an array with objects
    console.log(MyHue.Lights[l]);
    this.hueLights.push(MyHue.Lights[l]);
   }
  }

}

如果我尝试运行这个我得到错误

Cannot read property 'lights' of undefined

所以我认为嵌套的 ngFor 的语法是错误的。应该可以从上面调用 "group"。

编辑: 这是 MyHue.Groups 对象的重要部分:

{action:Object
 class:"Living room"
 lights: Array(2)
   0:"3"
   1:"1"
 name:"Room1"}

组对象中只有属于该组的灯的 ID

这是灯光对象外观的重要部分:

 {state: Object, type: "Extended color light", name: "Couch1", modelid: "LCT007"…}

这是我将孔数组打印到控制台时得到的结果:

Object {1: Object, 3: Object, 4: Object}

所以我必须匹配哪个灯光 ID 在哪个组中,然后检查灯光对象的名称

看起来您需要创建一个更简单的数据结构,其中您的灯光对象包含在 hueGroup 对象的数组 属性 中。然后您将能够轻松地遍历您的组,以及模板中的每个灯。

例如,您的模板应该更像这样:

<ul>
    <li *ngFor="let group of hueGroups">
    {{group.name}}
    <ul>
        <li *ngFor="let light of group.lights">
        {{light.name}}
        </li>
    </ul>
    </li>
</ul>

并且您的组件应包含 hueGroups 要呈现的数据对象或模型。

hueGroups = [{
    name: "group 1",
    lights: [{
      name: "light 1"
    },{
      name: "light 2"
    }]
  },
  {
    name: "group 2",
    lights: [{
      name: "light 3"
    },{
      name: "light 4"
    }]
  }];

查看这个 plunker 以了解我的意思的工作示例: http://plnkr.co/edit/THXdN8zyy4aQMoo4aeto?p=preview

这里的关键是使用您的模板来反映支持它的组件数据的内容。除了我的示例之外,您可能还想使用打字稿为您的群组和灯光定义界面或 class。

您的示例有点复杂,因为您的模板试图呈现两种数据结构的合成(您的 hueGroup.lights 似乎只是光 ID 的数组)。我建议制作一个函数来创建一个 hueGroup 对象,其中嵌入了您的模板可以轻松迭代的灯光对象。这是此类函数的示例:

已更新以反映示例数据:

ngOnInit(){
    this.hueGroups = this.hueGroupSource.map((group)=>{
      let lightObjects = group.lights.map((lightID)=>{
        return this.hueLightsSource.find((light, index) => {return index === lightID});
    });
    group.lights = lightObjects;
    return group;
  });

}

这是一个在工作示例中显示它的插件。 http://plnkr.co/edit/V309ULE8f6rCCCx1ICys?p=preview

我设法使用下面的嵌套 ngFors:

<ion-card *ngFor="let exercise of exercises">
    <ion-card-header>
      <ion-card-title>
        {{exercise.name}}
      </ion-card-title>
    </ion-card-header>
    <ion-item *ngFor="let set of exercise.sets">
      set: {{set.setNo}}
      reps: {{set.reps}}
      weight:{{set.weight}}
    </ion-item>
  </ion-card>