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

Angular嵌套响应式表单输入框无法绑定更新值如何解决?

问题根因

你使用了嵌套结构的响应式表单,id_warehouse是子分组war_id下的控件,模板中直接在顶层表单下用formControlName绑定该控件时,Angular只会在顶层FormGroup的控件列表中查找同名控件,找不到就会静默忽略输入同步,所以你输入的内容不会更新到表单模型中,显示的始终是初始化的默认值。

修复方案

有两种常用修复方式,任选其一即可:

方式1:使用formGroupName声明父分组(推荐)

在嵌套控件外层添加一个容器元素,用formGroupName指定所属的子分组名称,修改后对应代码如下:

<form [formGroup]="shelveForm" (ngSubmit)="onSubmit()">
{{shelveForm.value | json }}

<!-- input 1  -->
<input id="id_shelve" type="text" formControlName="id_shelve">

<!-- input 2-->
<input id="description" type="text" formControlName="description_shelve">

<!-- input 3  -->
<div formGroupName="war_id">
  <input id="description_war_id" type="text" formControlName="id_warehouse">
</div>

</form>

方式2:直接绑定控件实例

不需要额外添加容器,直接通过formControl属性绑定到对应的控件实例即可:

<!-- input 3  -->
<input 
  id="description_war_id" 
  type="text" 
  [formControl]="shelveForm.get('war_id.id_warehouse')"
>

修改完成后输入内容,war_id下的id_warehouse字段就会正常同步更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:51:02