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

Angular响应式表单动态字段存入FormArray的items数组实现问题

解决方案

1. 修改TypeScript代码

你现在的问题是把动态字段控件直接添加到了根FormGroup下,所以输出会出现在根级别。只需要把动态字段统一放到items FormArray内部的FormGroup中即可:

import { FormArray, FormGroup } from '@angular/forms';

// 表单初始化逻辑保持不变
this.testForm = this.formBuilder.group({
  start_date: ['', Validators.required],
  end_date: ['', Validators.required],
  call_direction: ['', Validators.required],
  items: this.formBuilder.array([])
})

// 新增:创建存放所有动态字段的FormGroup
const dynamicGroup = this.formBuilder.group({});
this.fields.forEach((x:any) => {
  // 把动态控件添加到内部的dynamicGroup,而不是根testForm
  const defaultValue = x.df_default === 'None' ? '' : x.df_default;
  dynamicGroup.addControl(x.df_name, new FormControl(defaultValue, Validators.required));
});
// 把组装好的动态字段组加入items数组
(this.testForm.get('items') as FormArray).push(dynamicGroup);

2. 修改HTML模板代码

因为动态控件现在归属在items数组的第0个FormGroup下,需要给动态字段区块增加对应的表单层级指向:

<!-- 指向form中的items FormArray -->
<ng-container formArrayName="items">
  <!-- 指向items数组的第0个元素(也就是我们刚才添加的动态字段组) -->
  <div [formGroupName]="0">
    <div class="row pt-2" *ngFor="let field of fields">
      <div class="col-4 d-flex align-items-center 13required">{{field.df_name}}&nbsp;  </div>
      <div class="col-6">
        <mat-form-field *ngIf="field.df_type == 'text'"  appearance="outline">
          <input matInput [type]="field.df_type" [formControlName]="field.df_name"  required/>
        </mat-form-field>
        <mat-form-field *ngIf="field.df_type == 'dropdown'"  appearance="outline">
          <mat-select [formControlName]="field.df_name" placeholder="">
            <mat-option
            [value]="option"
            *ngFor="let option of field.df_options"
            >
            {{ option }}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>
    </div>
  </div>
</ng-container>

修改完成后调用this.testForm.value就能得到你需要的输出结构。如果后续需要items数组存储多组动态字段,只需要往items FormArray中推入更多的FormGroup实例即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:18:03