从我的自定义组件中使用的父组件重新初始化formGroup时出现问题.我得到的错误是:
@H_301_1@
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
<我的定制-成分>是根据创建自定义formControl组件的有效方式创建的:https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#implementing-controlvalueaccessor
零件
这是初始化formGroup变量addForm的代码:
let formTemp: any = { selectedCompany: new FormControl(null,[Validators.required]),} this.addForm = this._formBuilder.group(formTemp);
我发现重复初始化formGroup并不好,因为组件会丢失对旧formGroup的引用.
如果设置值是显示新表单所需的值,则.setValue是此处的解决方案:
零件
而不是重新初始化addForm,检查addForm是否先前已初始化,如果是,则仅为现有FormControls设置值:
if (this.addForm) { this.addForm.setValue({ selectedCountry: null }) } else { let formTemp: any = { selectedCompany: new FormControl(null,} this.addForm = this._formBuilder.group(formTemp); }