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

While using ngFor - when removing item from array all directives on nested layout throw error

我的模板遍历组并呈现一些嵌套元素,列出 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

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

也许我做错了。 我想删除一个组并让所有嵌套元素都消失。 我该怎么做才是正确的?

谢谢

您可以使用 splice

而不是 delete this.groups[index]

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

区别看这个问题 Deleting array elements in JavaScript - delete vs splice