Search code examples
angularangular-formsform-controlangular-formbuilder

How to set dynamic fields and it values in form


  • I'm using angular form Control.
  • I have set of values to display in a form,few are static and few are dynamic.
  • I'm displaying static values with formControlName and and ts file I'm receiving in fb group as below.

For Known values I doing as below.

Html File

<input type = "text" formControlName="catalogItemId">

Ts File

this.catalog Form = this.fb.group({
catalogItemId:fb.control('').
.
.
so on
})

For Dynamic values(Unknown values),I'm looping then as below(since I don't know what are fields going come here).

<mat-list-item *ngFor="let data of attributeMap | keyvalue">
     <mat-form-field>
         <mat-label>{{data.key}}</mat-label>
         <input matInput type="text" value = {{data.value}}
     </mat-form-field>
</mat-list-item>

Now the Question is How can I get these dynamic values in my form group(i.e this.catalog Form )

I haven't used the form builders before and I'm looking through many articles to get this doubt cleared. Hoping a solution.Thanks in Advance.


Solution

  • You can use addControl() on your form, providing it two parameters (the name of the control and the control created). As you might want to loop over the dynamic controls only in the template, i would advice to create a nested formgroup inside your form to isolate it from the static controls of your form.

    this.catalogForm = this.fb.group({
     catalogItemId:fb.control(''),
     dynamicControls: this.fb.group({})
    });
    
    addDynamicValues() {
     for (let key in attributeMap) {
      (this.catalogForm.get('dynamicControls') as FormGroup).addControl(key, this.fb.control(attributeMap[key]))
      }
    }
    
    

    Then in template :

    <form [formGroup]="catalogForm">
     <section formGroupName="dynamicControls">
      <ng-container *ngFor=let control of catalogForm.get('dynamicControls').controls | keyvalue">
       <mat-form-field>
        <mat-label>{{control.key}}</mat-label>
        <input matInput type="text" [formControlName]="control.key"
       </mat-form-field>
     </ng-container>
    </section>
    </form>
    

    Working example on stackblitz