angular9 ngfor 从数组中删除对象显示未定义错误

angular9 ngfor removing object from array shows undefined error

我有一个对象数组。 这些项目是从服务调用的,并在我进入购物车页面时显示。

当我点击删除按钮时,我 运行 delete this.cart.items[i];。 this.cart 是我的服务,从对象中删除项目。它也在页面上成功地做到了这一点,但是我在控制台中得到了一个空白元素和错误,说 Cannot read property 'qty' of undefined。 我假设 ngfor 将自动更新 DOM 并删除元素,因为该对象不再存在。 我还必须手动从 DOM 中删除元素吗?

从下面的数组中,我想完全删除第一项但仍显示第二项。

[
  {
    "desc": "Description",
    "item": "item 1",
    "id": "1",
    "portion": "small",
    "price": "4.25",
    "qty": 3
  },
  {
    "desc": "Description",
    "item": "item 2",
    "id": "2",
    "portion": "large",
    "price": "4",
    "qty": 1
  }
]


<div class="cart-item" *ngFor="let item of items" (click)='ontap(item);'>
    {{ x.item }}
</div>

这是我显示它的地方,但它仍然显示没有数据的元素。 谢谢

delete this.cart.items[i] 不是从数组中删除元素的正确方法 delete 语句删除了项目但数组的长度仍然相同

this.cart.items.splice(i,1);

如果您在 dumb 组件中使用 onPush 策略,则 DOM 中的值将不会更新。

你必须这样写,例如:

let itemsWithoutRemoved = this.cart.items.splice(i, 1);

this.cart = {
...this.cart,
items: itemsWithoutRemoved 
}

然后您的视图将随着输入的更改而更新。

此外,从数组中删除一个项目是通过 splice 方法完成的。

ngFor 与索引一起使用以获取按钮点击的索引:

<div class="cart-item" *ngFor="let item of items; let i = index" (click)='onRemove(i);'>
    {{ x.item }}
</div>

然后使用该索引从数组中删除并将结果数组重新分配给它自己:

onRemove(index: number) {
   this.items = [...this.items.splice(index, 1)]
}

注意: 展开运算符用于触发 Angular 上的变化检测。