【问题标题】:Delete row - always deletes the last row as index returns -1删除行 - 总是在索引返回 -1 时删除最后一行
【发布时间】:2019-04-25 05:33:50
【问题描述】:

我的 Angular 应用程序中有一个响应式表单,其中一个问题允许用户添加或删除行。每行都有一个删除按钮。我面临的问题是,当我单击特定项目上的删除按钮时,它将删除最后一行。我在函数处做了断点,它显示索引为-1,我知道这意味着最后一项将被删除。

delete_communityList_row(id) {
  const index = this.Form.value.communityList.indexOf(id);
  this.Form.value.communityList.splice(index, 1);
}

单击删除按钮时,“id”返回我单击的行的 id,因此我不能完全显示出了什么问题。这是 console.log 输出,它返回一个对象数组。

【问题讨论】:

  • 我认为communityList 持有对象
  • 分享你的模板代码
  • @PranavCBalan 是的,它确实返回了一个对象数组。如何使用 splice 从数组中删除对象?
  • 分享您的模板
  • 一种方法是const index = this.Form.value.communityList.findIndex(o => o.id === id); .... 有更好的解决方案是分享您的模板

标签: angular typescript


【解决方案1】:

在您的代码中,communityList 属性包含对象集合,并且您正在检查数组中不作为元素存在的 id(可能是字符串或数字)的索引(它是对象的属性值),因此它总是返回-1。根据Array#splice 文档,如果起始值为负数,则从末尾开始计数,如array.length - n-1 表示最后一个索引)。

您可以通过使用Array#findIndex 方法检查属性值来获取索引,该方法遍历数组并在回调返回true 时返回索引。

const index = this.Form.value.communityList.findIndex(o => o.id === id);

最终代码:

delete_communityList_row(id) {
  const index = this.Form.value.communityList.findIndex(o => o.id === id);
  if(index !== -1) this.Form.value.communityList.splice(index, 1);
}

仅供参考:如果您从模板调用方法(使用*ngFor 生成),那么您可以传递index 而不是id,这样会更简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 2017-01-20
    • 2019-07-23
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多