【问题标题】:Angular2 single ngFor for multiple arraysAngular2 单个 ngFor 用于多个数组
【发布时间】:2017-09-13 02:01:33
【问题描述】:

是否可以在 Angular 中为 ngFor 使用多个数组?

   *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 对象,从中我需要显示区域内的所有设备和设备。

【问题讨论】:

  • 那些expressions类似于JavaScript;你对arr1 && arr2.devices 有什么期望?
  • @jonrsharpe 我已经更新了我的问题

标签: javascript angular angular2-directives ngfor


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以连接两个数组,如下所示

    this.elements= arr1.concat(arr2);
    

    此外,为了避免undefined 错误,您应该使用 ? 类型安全运算符,如下所示

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

    【讨论】:

    • 如果在 concat 之后列表元素发生了变化怎么办?我该如何处理这种情况?
    • 通过改变你到底是什么意思
    • "Element" 我得到了@Input。用户可以将设备添加到此元素,也可以再次添加包含设备的区域。我需要将设备(独立)和位于区域内并以 html 显示的设备结合起来。如果用户添加或删除设备,则列表应更新。
    • @PratapA.K 如果您将所有设备连接到一个变量中,我们将其称为设备,然后迭代该 *ngFor="let device of devices" 然后更改检测将运行新设备或删除。
    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 2017-09-20
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2021-06-25
    • 2016-05-26
    相关资源
    最近更新 更多