3

I am using angular reactive forms and I have form structure like below.

{  
   "name": '',  
   "params": {}  
}

I want to add dynamic properties(form controls) inside params formGroup. Below is the code I used but it's giving empty controls object.

ts file

exercise = {
    data:[
      {param: "Reps"},
      {param: "Tempo"}
    ],
};

{
   this.exerciseForm = this.formBuilder.group({
      name: ['', [Validators.required],
      params: this.formBuilder.group({})
   });
}

get getAllParams(){
  return this.exerciseForm.get('params') as FormGroup;
} 

addNewParam(){
  this.getAllParams[param] = this.formBuilder.control('');
}

template file

<div formGroupName="params" *ngFor="let param of exercise.data;">
    <input type="text" [formControlName]="param.param" />
</div>

Can anyone please help me to create the same structure?

4
  • for add a control to a formGroup use 'addControl' angular.io/api/forms/FormGroup#addcontrol, e.g. this.exerciseForm.addControl('temp',new FormControl('')) Commented Oct 3, 2019 at 8:31
  • Not working. Input fields are not rendering on UI. And control is also not adding. Do I need to change anything in HTML template? Commented Oct 3, 2019 at 8:34
  • But I want my params to be a object as you can see. Commented Oct 3, 2019 at 8:44
  • rajat, I put my comment in form of answer Commented Oct 3, 2019 at 8:45

1 Answer 1

6
//At first only "name" and a formGroup "params" empty
this.exerciseForm = this.formBuilder.group({
  name: ["", [Validators.required]],
  params: this.formBuilder.group({})
});

this.exercise.data.forEach(param => {
  (this.exerciseForm.get("params") as FormGroup).addControl(
    param.param,
    new FormControl()
  );
});

see stackblitz

Updated: the .html like

<form [formGroup]="exerciseForm">
  <input formControlName="name">
  <div formGroupName="params">
  <div *ngFor="let param of this.exercise.data">
    <input [formControlName]="param.param">
  </div>
  </div>
</form>

<pre>
  {{exerciseForm?.value|json }}
</pre>

*Update 2 to avoid errors We can add an *ngIf to the input

  <input *ngIf="exerciseForm.get('params.'+param.param)"
    [formControlName]="param.param">

Another aproach is loop over controls using keypipe value

<form [formGroup]="exerciseForm2">
  <input formControlName="name">
  <div formGroupName="params">
  <div *ngFor="let control of exerciseForm2.get('params').controls|keyvalue;let i=index">
    <input [formControl]="control.value">
  </div>
  </div>
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

I updated again the answer and the stackblitz. choose whatever you want, loop over params or over controls, but is you want to add a label, you need correlation the params and the index
Can you please help me with one more query?
which query? I'll try it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.