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

Angular点击按钮删除数组元素功能代码出错怎么解决?

问题原因
  • *ngFor语法位置写错。你把内层的*ngFor="let newTask of todo; index as i"直接写在了<div>标签的内部文本位置,没有作为标签属性放在尖括号里,Angular不会解析这段语法,你拿到的索引i是无效值。
  • 嵌套了两层不必要的*ngFor遍历。外层已经对todo数组做了遍历渲染每个条目,内层又重复遍历一次todo数组,会导致每个条目下都渲染出和数组长度一致的删除按钮,逻辑完全错误。
  • 没有在外层的遍历声明里获取当前项的索引。外层的*ngFor="let item of todo"没有声明索引变量,根本拿不到当前点击条目对应的数组下标。
修复方案

模板代码直接修改为如下写法即可,TS部分的onDeleteTask逻辑不需要调整:

<div
  class="example-box"
  *ngFor="let item of todo; index as i" 
  cdkDrag
>
  {{item}} 
  <div>
    <button class="remove" mat-flat-button color="warn" (click)="onDeleteTask(i)">X</button>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 21:54:03