我使用一个数组来存储一组对象和一个列表的光对象。 我想在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]);
}
}
如果我尝试运行这个程序,我会遇到以下错误:
无法读取未定义属性“lights”
因此,我认为嵌套ngFor的语法有误。应该可以从上面调用“group”。
编辑: 这是MyHue.Groups对象的重要部分:
{action:Object
class:"Living room"
lights: Array(2)
0:"3"
1:"1"
name:"Room1"}
在Group对象中,只有依赖于该组的灯的ID。
这是灯对象的重要部分:
{state: Object, type: "Extended color light", name: "Couch1", modelid: "LCT007"…}
如果我将整个数组打印到控制台上,我会得到以下内容:
Object {1: Object, 3: Object, 4: Object}
所以我需要匹配哪个 Light ID 属于哪个组,并检查灯光对象的名称。
*ngFor
与一个object
。*ngFor
只能用于Arrays
。你可以创建一个管道并使用*ngFor
来迭代hueLights
的键。 - developer033hueLights
和hueGroups
的内容,这样更容易理解。 - developer033