带有嵌套 FormGroup 的 FormArray。如何访问嵌套的表单组控件?

问题描述 投票:0回答:1

我有一个包含 3 个 FormGroup 的 FormArray,每个表单组有 2 个控件。我不确定如何访问表单组中的控件来设置表单控件名称。

设置表格

this.form = this.formBuilder.group({
---a couple controls---
properties: this.formBuilder.array({
  first: this.formBuilder.group({ 
   label: new UntypedFormControl(),
   value: new UntypedFormControl(),
  }),
  second: this.formBuilder.group({ 
   label: new UntypedFormControl(),
   value: new UntypedFormControl(),
  }),
  third: this.formBuilder.group({ 
   label: new UntypedFormControl(),
   value: new UntypedFormControl(),
  }),
})
})

数组属性的 getter

get properties() {
  return this.form.controls.properties as FormArray;
}

我能够添加和删除一行属性。

html 为表单。我不确定如何从表单数组访问每个表单组中的标签和值控件。

<div formArrayName="properties">
  <ng-container *ngFor="let propertiesForm of properties.controls; let i = index">
  <div [formGroupName]="i">
---then I have 3 sets of mat form fields each with and label and value---
  </div>
  </ng-container>
</div>
angular angular-reactive-forms formarray form-control formgroups
1个回答
0
投票

this.formBuilder.array()
方法只接受一个数组参数。您无法为其提供对象。

方法 1:使用

this.formBuilder.array([])

  1. 将您的
    properties
    结构修改为数组。
  2. 您可以使用循环在
    FormGroup
    properties
    中添加所需的
    FormArray
    数量。您应该考虑实现一个函数来生成单个属性
    FormGroup
    。这样做的目的是减少代码冗余。
ngOnInit() {
  // Form with Form Array
  this.form = this.formBuilder.group({
    //---a couple controls---
    properties: this.formBuilder.array([]),
  });

  for (let i = 0; i < 3; i++)
    this.properties.push(this.createPropertyFormGroup());
}

createPropertyFormGroup() {
  return this.formBuilder.group({
    label: new UntypedFormControl(),
    value: new UntypedFormControl(),
  });
}
<form [formGroup]="form">
  <div formArrayName="properties">
    <ng-container
      *ngFor="let propertiesForm of properties.controls; let i = index"
    >
      <div [formGroupName]="i">
        <label>Label: </label>
        <input formControlName="label" />
        <br />

        <label>Value: </label>
        <input formControlName="value" />
      </div>
      <hr />
    </ng-container>
  </div>
</form>

方法 2:使用

this.formBuilder.group({})

  1. 在 HTML 中,您需要
    KeyValuePipe
    来迭代属性
    FormGroup
    对象并生成每个
    FormGroup
this.form = this.formBuilder.group({
  //---a couple controls---
  properties: this.formBuilder.group({
    first: this.createPropertyFormGroup(),
    second: this.createPropertyFormGroup(),
    third: this.createPropertyFormGroup(),
  }),
});
<form [formGroup]="form">
  <div formGroupName="properties">
    <ng-container
      *ngFor="let propertiesForm of propertiesFormGroup.controls | keyvalue;"
    >
      <div [formGroupName]="propertiesForm.key">
        <label>Label: </label>
        <input formControlName="label" />
        <br />

        <label>Value: </label>
        <input formControlName="value" />
      </div>
      <hr />
    </ng-container>
  </div>
</form>

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.