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

Angular添加数组元素后[(ngModel)]不显示tableInputRow.name值问题

问题解决:ngModel绑定name字段异常

问题现象

向数组添加NewTableInputRow对象后,tableInputRow.name的值无法通过[(ngModel)]正常显示,但tableInputRow.priority的值显示正常。编辑前两个字段再添加新字段时,新增行的任务名称输入框绑定失效,优先级输入框则正常显示默认值5。

问题原因

Angular中使用[(ngModel)]绑定表单控件时,每个控件的name属性必须唯一:

  • 优先级输入框的name设置为priority-{{index}},通过索引保证了每行控件的唯一性,因此绑定正常;
  • 任务名称的输入框和textarea的name是固定值row-name和row-name-expanded,新增行后多个控件共用同一name,导致ngModel绑定混乱,无法正常同步值。

修复方案

修改模板中任务名称输入控件的name属性,加入索引确保唯一性:

修改后的核心模板代码

<div class="regular-row" *ngIf="!tableInputRow.expanded">
  <input
    [required]="!index"
    [(ngModel)]="tableInputRow.name"
    name="row-name-{{index}}" <!-- 加入索引保证唯一 -->
    class="form-control"
    type="text"
    placeholder="Task Name">
    <i class="fa fa-expand" (click)="onRowExpandColToggle(index)" aria-hidden="true"  title="Expand input height"></i>
</div>
<div class="expand-row" *ngIf="tableInputRow.expanded">
  <textarea
    [required]="!index"
    [(ngModel)]="tableInputRow.name"
    name="row-name-expanded-{{index}}" <!-- 加入索引保证唯一 -->
    class="form-control"
    placeholder="Expanded Task Name">
  </textarea>
  <i class="fa fa-compress" (click)="onRowExpandColToggle(index)" title="Collapse input height" aria-hidden="true"></i>
</div>

优化建议

可以将NewTableInputRow类中name的默认值从undefined改为空字符串'',避免输入框初始状态出现undefined的文本:

export class NewTableInputRow{
  constructor(
    public name='',
    public priority=5,
    public lastEdit = undefined,
    public expanded = false,
  ) {}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:54:55