You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular表单数组删除指定项异常:点击删除总是移除第一项

问题原因与修复方案

嘿,这个问题其实一眼就能找到症结——你在点击删除按钮时,没把当前行的索引传递给删除方法!

1. 核心问题:未传递索引参数

你的组件方法removeMobile(index: number)明明需要接收要删除项的索引才能定位到具体行,但模板里的点击事件写的是(click)="removeMobile()",完全没传循环里的i(当前行的索引)。这时候方法里的index参数会默认是undefined,调用removeAt(index)时,undefined会被转换成0,自然每次都删掉第一个项。

2. 模板代码修改

把删除按钮的点击事件改成传递当前索引i:

<div formArrayName="mobiles">
  <div *ngFor="let mobile of mobiles.controls; let i = index" [formGroupName]="i">
    <div class="d-flex align-items-center" [class.pt-4]="i > 0">
      <input class="input" type="text" formControlName="phone">
      <a class="input-remove ml-3">
        <!-- 这里传入当前行的索引i -->
        <i class="icon icon-trash h3 text-primary" (click)="removeMobile(i)"></i>
      </a>
    </div>
  </div>
</div>

如果你的stations列表也有对应的删除按钮,记得同样把removeStation()改成removeStation(i)。

3. 组件方法的额外小bug

另外,我注意到你的removeStation方法里有个逻辑错误:

removeStation(index: number) {
  this.stations.removeAt(index);
  // 这里应该判断stations的长度,而不是mobiles!
  if (this.mobiles.controls.length == 0) { 
    this.addStation();
  }
}

把判断条件改成this.stations.controls.length == 0,这样删除最后一个station时才会自动添加新的项。

这样修改后,点击删除按钮就会精准删除你选中的那一行啦!

内容的提问来源于stack exchange,提问作者Tanasos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:57:56