Custom FormControl component breaks if re-initialization of FormGroup from parent

I am having a problem re-initializing a formGroup from a parent component that is being used in my custom component. The error I am getting:

No FormControl instance attached to form control with name: 'selectedCompany'

Html

<form [formGroup]="addForm">
     ...
     <my-custom-component formControlName="selectedCompany"></my-custom-component>
     ...
</form

      

<my-custom-component>

is generated according to the valid way to create a custom formControl component: https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#implementing-controlvalueaccessor

Component

This is the code that initializes the formGroup variable addForm

:

let formTemp: any = {
    selectedCompany: new FormControl(null, [Validators.required]),
}

this.addForm = this._formBuilder.group(formTemp);

      

Initially initialized addForm

, that's all good. But when I reopen the modal form where the form is located and the same component code is executed, the above error occurs.

+3


source to share


1 answer


I realized that it is not recommended to re-initialize the formGroup over and over again because the component loses its reference to the old formGroup.

If you need parameter values ​​to display the new form, .setValue

here:

Component



Instead of reinitializing, addForm

check if it was previously initialized addForm

, and if so, set only the value for the existing one FormControls

:

if (this.addForm) {
    this.addForm.setValue({
        selectedCountry: null
    })
} else {

    let formTemp: any = {
        selectedCompany: new FormControl(null, [Validators.required]),
    }

    this.addForm = this._formBuilder.group(formTemp);
}

      

This way I figured out the link is not lost for the old one addForm

, so no error occurs.

+6


source







All Articles