【问题标题】:angular9 ngfor removing object from array shows undefined errorangular9 ngfor 从数组中删除对象显示未定义的错误
【发布时间】:2020-08-23 20:29:48
【问题描述】:

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

当我单击删除按钮时,我运行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>

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

【问题讨论】:

  • 你能分享一些代码吗?
  • 你有没有试过删除这样的项目this.cart.items.splice(i,1);

标签: angular typescript ngfor


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    你必须这样写,例如:

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

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

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

    【讨论】:

      【解决方案3】:

      使用带有索引的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 上的更改检测。

      【讨论】:

        猜你喜欢
        • 2016-08-18
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 2011-02-24
        • 2021-03-28
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多