How to add a FormGroup to a FormArray without triggering form change event

Viewed 2908

I initialise a form with any empty array in definitionProperties how can I update FormGroup? I need to do so without triggering a change event otherwise it causes an infinite loop in the valueChanges observable.

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

This causes the infinite loop:

this.gridProcessorForm.valueChanges.subscribe(val => {
    let propertyGroups: FormGroup[] = [];
    for (let property of this.objectDefinition.properties) {
      let group = this.createPropertyFormGroup(property);
      (this.gridProcessorForm.get('definitionProperties') as FormArray).push(group); // triggers change event so infinite loop
    }
});

When using setValue with { emitEvent: false } to overwrite the FormArray it gets an error.

this.gridProcessorForm.valueChanges.subscribe(val => {
  if (this.gridSideSelection = 'top') {        
    let propertyGroups: FormGroup[] = [];
    for (let property of this.objectDefinition.properties) {
      let group = this.createPropertyFormGroup(property);
      propertyGroups.push(group);
    }

    (this.gridProcessorForm.get('definitionProperties') as FormArray).setValue(propertyGroups, { emitEvent: false });
  }
});

I get this error:

There are no form controls registered with this array yet. 

It seems it requires the form builder to initialise with a group in the FormArray? But I want to initialise the form with everything empty.

2 Answers

I hope this will help as this is my running code.

    let containersArray = <FormArray>this.formName.controls['containers'];
    containersArray.push(this.addContainerInitialize(container));


addContainerInitialize(value) {

    return this.fb.group({
        containerNumber: [value.containerNumber],
        conType: [value.conType, Validators.required],
        quantity: [value.noOfContainers, Validators.required],
        weight: [value.grossWeight, Validators.required]
    });
}
Related