Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a FormArray to an array of FormGroups

Tags:

angular

How can I set a FormArray of a FormGroup? I want to set definitionProperties (FormArray) of my form.

this.processorForm = this.fb.group({
    propertiesSide: new FormControl(),
    objectNamesSide: new FormControl(),
    definitionProperties: this.fb.array([])
});

The FormArray of FormGroups:

let propertyControls: FormGroup[] = [];
propertyControls = getFormGroups(); // set definitionProperties to this

I found some code to add one by one but I'd like to set with an array rather than one value using push if it's possible:

(this.gridProcessorForm.get('definitionProperties') as FormArray).push(group)

The getFormGroups() function builds an array of groups:

createPropertyFormGroup(definitionProperty: ObjectDefinitionProperty) {
   let formGroup = this.fb.group({
      propertyName: definitionProperty.name,
      propertyType: definitionProperty.type.name,
      gridOffset: 1
   });
   return formGroup;
}

The setting of the FormArray is in an observable:

this.gridProcessorForm.valueChanges.subscribe(...)
like image 273
doe Avatar asked Mar 04 '26 19:03

doe


1 Answers

Try this for initial Setup

this.processorForm = this.fb.group({
    propertiesSide: new FormControl(),
    objectNamesSide: new FormControl(),
    definitionProperties: this.fb.array([
         this.fb.group({
             propertyName: definitionProperty.name,
             propertyType: definitionProperty.type.name,
             gridOffset: 1
         })
   })])
});

Use this for Adding more:

 var _definitionProperties= <FormArray>this.processorForm .controls.definitionProperties;
_definitionProperties.push({
       this.fb.group({
             propertyName: 'Name',
             propertyType: 'Type',
             gridOffset: 1
         })
 })

For more info read this: https://medium.com/@m.kunwa52/reactive-form-in-angular-with-formarray-2595e5ee1d31

like image 159
Mustafa Kunwa Avatar answered Mar 07 '26 09:03

Mustafa Kunwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!