How to use array of objects for controls in Reactive Forms

You need to add a FormGroup, which contains your label and value. This also means that the object created by the form, is of the same build as your fields object.

ngOnInit() {
  // build form
  this.userForm = this.fb.group({
    type: this.fb.group({
      options: this.fb.array([]) // create empty form array   
    })
  });

  // patch the values from your object
  this.patch();
}

After that we patch the value with the method called in your OnInit:

patch() {
  const control = <FormArray>this.userForm.get('type.options');
  this.fields.type.options.forEach(x => {
    control.push(this.patchValues(x.label, x.value))
  });
}

// assign the values
patchValues(label, value) {
  return this.fb.group({
    label: [label],
    value: [value]
  })    
}

Finally, here is a

Demo

Leave a Comment