Search code examples
angularformsform-controlformgroups

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


I want formControlName Like this,

  • field_0
  • field_1
  • field_2

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


Solution

  • 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