简体   繁体   中英

Angular2 single ngFor for multiple arrays

Is it possible to use multiple array's for ngFor in Angular?

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

I'll be having access to Element object, from that I need to display all the devices and devices inside zones.

使用concat连接两个数组,然后ngFor使用ngFor

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

You can concatenate two arrays as below

this.elements= arr1.concat(arr2);

In addition, to avoid the undefined error you should be using ? type safe operator as below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM