1

我想要 formControlName 像这样,

  • 字段_0
  • 字段_1
  • 字段_2

myObj = { "field_0":"value_0", "field_1":"value_1", "field_2":"value_2", } }

4

2 回答 2

2

以下是使用 a 的示例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用作索引。然后我可以使用字段i中的id来定义一个唯一的 ID。

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

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

你可以在这里找到完整的例子:https ://github.com/DeborahK/Angular-ReactiveForms/tree/master/Demo-Final

于 2018-12-11T06:48:57.703 回答
2

如果你有一些喜欢

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}}

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

stackblitz

于 2018-12-11T07:54:03.150 回答