gpt4 book ai didi

Angular2 嵌套 *ngFor

转载 作者:太空狗 更新时间:2023-10-29 17:32:30 26 4
gpt4 key购买 nike

我使用一个数组来存储组对象列表和一个灯光对象列表数组。我想在 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 的语法是错误的。应该可以从上面调用“组”。

编辑:这是 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

这里的关键是使用您的模板来反射(reflect)支持它的组件数据的内容。除了我的示例之外,您可能还想使用 typescript 为您的群组和灯光定义接口(interface)或类。

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

已更新以反射(reflect)示例数据:

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;
});

}

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

关于Angular2 嵌套 *ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44272911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com