2017-04-17 45 views
0

是否有可能在Angular中使用ngForum的多個數組?Angular2單ngForFor多個陣列

*ngFor="let device of element.devices && element.zones.devices"// something like this 

export interface Element { 
    id: string; 
    name: string; 
    zones: Zone[]; 
    devices: Device[]; 
} 

export class Zone { 
    id: string; 
    name: string; 
    devices: Device[]; 
} 

export class Device { 
    id: string; 
    name: string; 
} 

我將有權訪問Element對象,我需要顯示區域內的所有設備和設備。

+0

那些[表達式](https://angular.io/docs/ts/latest/guide/template-syntax.html#!#template-expressions)類似於JavaScript的;你會從'arr1 && arr2.devices'期待什麼? – jonrsharpe

+0

@jonrsharpe我已經更新了我的問題 –

回答

5

使用concat連接兩個數組,然後用ngFor在它

*ngFor = "let device of arr1.concat(arr2.devices)" 
0

您可以連接兩個數組如下

this.elements= arr1.concat(arr2); 

此外,爲避免您應該使用undefined錯誤?類型安全操作如下

<div *ngFor="let device of elements?.devices"> 
    <span> {{device?.name}} </span> 
</div> 
+0

如果列表元素在我進行concat後發生了變化,該怎麼辦?我該如何處理這種情況? –

+0

通過改變你到底意味着什麼 – Aravind

+0

我得到@Input的「元素」。用戶可以將設備添加到此元素,或者可以再次添加包含設備的區域。我需要將兩個設備(獨立的)和設備組合在一起,並在html中顯示。如果用戶添加或刪除設備,則應更新列表。 –