Custom component FormControl breaking if reinitializing FormGroup from parent

Mario Petrovic picture Mario Petrovic · Jun 1, 2017 · Viewed 8.7k times · Source

I got a problem when reinitializing formGroup from parent component that is used in my custom component. Error that i get is:

There is no FormControl instance attached to form control element with name: 'selectedCompany'

HTML:

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

<my-custom-component> is created according to valid way of creating custom formControl component: https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#implementing-controlvalueaccessor

Component

This is code that initializes formGroup variable addForm:

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

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

First time addForm is initialized all is good. But when i reopen modal where form is located, and same component code is executed, above mentioned error occurs.

Answer

Mario Petrovic picture Mario Petrovic · Jun 1, 2017

I figured out that it is not good to reinitialize formGroup over and over again, because component looses reference to old formGroup.

If setting values is what is needed to show fresh form, .setValue is the solution here:

Component

Instead of reinitializing addForm, check if addForm was initialized previously and if so, only set value for existing 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);
}

In this way, I figured, reference is not lost to old addForm, so no error occurs.