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

ε祈祈猫儿з 提交于 2019-12-11 12:09:04

问题


I want formControlName Like this,

  • field_0
  • field_1
  • field_2

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


回答1:


if you have some like

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

You first must create a FormGroup

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

And, when you want show it

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

Well, we can replace fields by an array of objects with label","field","value" to create the form

See stackblitz




回答2:


Here is an example of using 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>

The form array is defined as addresses in this example.

The ngFor processes each address in the array, using i as the index. I can then use the i in the id field to define a unique id.

Each form array element is a form group.

The form group includes each element for an address. (I am only showing one of those elements here.)

You can find the complete example here: https://github.com/DeborahK/Angular-ReactiveForms/tree/master/Demo-Final



来源:https://stackoverflow.com/questions/53718663/angular-6-how-to-use-formgroup-to-create-formcontrolname-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!