Angular 6:如何使用FormGroup动态创建formControlName?

Angular 6: How to use FormGroup to create formControlName dynamically?

我想要这样的 formControlName,

我的对象 = { "field_0":"value_0", "field_1":"value_1", "field_2":"value_2", } }

这里是一个使用 formArray 的例子:

    <div formArrayName="addresses"
         *ngFor="let address of addresses.controls; let i=index">

      <div [formGroupName]="i">
        <div class="form-group row mb-2">
          <label class="col-md-2 col-form-label"
                 attr.for="{{'street1Id' + i}}">Street Address 1</label>
          <div class="col-md-8">
            <input class="form-control"
                   id="{{'street1Id' + i}}"
                   type="text"
                   placeholder="Street address (required)"
                   formControlName="street1"
                   [ngClass]="{'is-invalid': (address.controls.street1.touched || 
                                              address.controls.street1.dirty) && 
                                              !address.controls.street1.valid }">
            <span class="invalid-feedback">
              <span *ngIf="address.controls.street1.errors?.required">
                Please enter your street address.
              </span>
            </span>
          </div>
        </div>
      </div>
    </div>

本例中表单数组定义为addresses

ngFor 处理数组中的每个地址,使用i 作为索引。然后,我可以在 id 字段中使用 i 来定义唯一 ID。

每个表单数组元素都是一个表单组。

表单组包括地址的每个元素。 (我在这里只展示其中一个元素。)

您可以在此处找到完整的示例:https://github.com/DeborahK/Angular-ReactiveForms/tree/master/Demo-Final

如果你喜欢

fields=["field_0","field_1","field_2"]

您首先必须创建一个 FormGroup

  createForm(fields: string[]) {
    let group: any = {};
    fields.forEach(x => {
      group[x] = new FormControl();
    })
    return new FormGroup(group);
  }

而且,当你想显示它时

<form [formGroup]="form">
  <div *ngFor="let field of fields">
    <input [formControlName]="field">
  </div>
</form>
{{form?.value|json}}

好吧,我们可以用带有标签的对象数组替换字段,"field","value"来创建表单

stackblitz