You need to enable JavaScript to run this app. Angular响应式表单中如何将FormControl存储的对象数组的name字段绑定到input
优惠活动
大模型
产品
解决方案
定价
更多

Angular响应式表单中如何将FormControl存储的对象数组的name字段绑定到input

问题原因

你当前的写法存在两处核心问题导致绑定失败:

  1. formControlName 只能匹配所属父 FormGroup 中预先定义的表单控件键名,你直接填写director.name并不是表单中存在的控件键,自然无法绑定
  2. 你将整个director数组存在单个FormControl中,不符合Angular响应式表单的数组结构规范,无法直接通过formControlName绑定数组子项的字段

方案1:快速修复(适合不需要编辑director字段的场景)

因为你的input设置了disabled只读,不需要双向绑定修改值,直接替换input的绑定方式即可,无需修改TS代码:

<div *ngFor="let director of companyDetailsForm.controls['directors'].value; let i = index" class="form-group start-aligned" style="margin-left: 69px;margin-right: 69px">
    <label>{{'Director' | localize}} {{i+1}}</label>
    <!-- 去掉formControlName,直接用[value]绑定属性 -->
    <input disabled type="text" class="form-control" pInputText [value]="director.name" />
</div>

方案2:响应式表单规范改造(适合后续需要编辑director信息的场景)

如果后续需要支持修改、校验director的字段,建议把directors改造成FormArray结构,符合Angular响应式表单的设计规范:

第一步:修改TS代码

// 顶部先导入所需的表单类
import { FormArray, FormGroup, FormControl } from '@angular/forms';

// 构造表单时将directors改为FormArray类型
this.companyDetailsForm = new FormGroup({
  directors: new FormArray(
    // 遍历后端返回的director数组,每个子项对应一个FormGroup
    (response?.companyDirectors || []).map(director => 
      new FormGroup({
        id: new FormControl(director.id),
        name: new FormControl(director.name)
      })
    )
  )
});

// 可选:封装getter简化模板中获取FormArray的代码
get directorsArr(): FormArray {
  return this.companyDetailsForm.get('directors') as FormArray;
}

第二步:修改HTML模板

<!-- 遍历FormArray的控件,指定每个子FormGroup的索引为组名 -->
<div *ngFor="let directorGroup of directorsArr.controls; let i = index" [formGroupName]="i" class="form-group start-aligned" style="margin-left: 69px;margin-right: 69px">
    <label>{{'Director' | localize}} {{i+1}}</label>
    <!-- formControlName匹配子FormGroup里定义的name键 -->
    <input disabled type="text" class="form-control" pInputText formControlName="name" />
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 07:21:01