2
  • 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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Gérôme Grignon,Thanks for the response,I have done the same you have given and I can populate the details successfully,but they are the patching the values, how can I do it for the dynamic values.
i don't clearly understand your question, may you try to reformulate it please?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.