代码之家  ›  专栏  ›  技术社区  ›  bravik

使用ngFor时-从数组中删除项时,嵌套布局上的所有指令抛出错误

  •  0
  • bravik  · 技术社区  · 8 年前

    我的模板遍历组并呈现一些嵌套元素,列出e.t.c.:

    <ul>
    <li *ngFor="let group of groups">
    ...
        <ul class="list_devices">
            <li class="row list_devices_header" *ngIf="getNumberOfDevicesInGroup(group.id) > 0">
                                    ...
            </li>
            <li class="row" *ngFor="let item of devices | matchesGroup:group.id">
                         ...
            </li>
        </ul>
    </li>
    </ul>
    

    问题是,当我从数组中删除组时:

    delete this.groups[index]
    

    渲染的布局仍然存在,并抛出错误:

    DeviceListComponent.html:122 ERROR TypeError: Cannot read property 'id' of undefined
    

    对于使用已删除对象的嵌套指令。

    也许我做错了。 我想删除一个组并删除所有嵌套元素。 我该怎么做才对?

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Bunyamin Coskuner    8 年前

    而不是 delete this.groups[index] 你可以用 splice

    试试这个 this.groups.splice(index, 1)

    要了解差异,请查看此问题 Deleting array elements in JavaScript - delete vs splice

    推荐文章