Custom component FormControl breaking if reinitializing FormGroup from parent

My solution for that is to replace formControlName with formControl.

Instead of

<my-custom-component formControlName="selectedCompany"></my-custom-component>

use

<my-custom-component [formControl]="addForm.controls['selectedCompany']"></my-custom-component>

or with some getMethod for taking formControl

Works also with error:

There is no FormControl instance attached to form control element with path

where I've used some FormArray.


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.