使用PatchValue时,Angular Responsive Forms AddControl会导致ExpressionChangedTerrithasBeenCheckedError
我希望能够使用组件构建一个反应式表单,但不是将其全部设置在一个父组件中。因此,我创建了初始使用PatchValue时,Angular Responsive Forms AddControl会导致ExpressionChangedTerrithasBeenCheckedError,angular,angular5,angular-reactive-forms,angular-changedetection,Angular,Angular5,Angular Reactive Forms,Angular Changedetection,我希望能够使用组件构建一个反应式表单,但不是将其全部设置在一个父组件中。因此,我创建了初始FormGroup并将其传递给组件,然后组件执行this.form.addControl(this.fb.group({…}))将其组添加到表单中 示例 父组件 this.form = this.fb.group({}); // Empty public ngAfterViewInit() { // Throws error after trying to patchValue on the chil
FormGroup
并将其传递给组件,然后组件执行this.form.addControl(this.fb.group({…}))
将其组添加到表单中
示例
父组件
this.form = this.fb.group({}); // Empty
public ngAfterViewInit() {
// Throws error after trying to patchValue on the child component
this.form.get('example').patchValue({
field1: 'Hello World!'
});
}
子组件
this.parentFormGroup.addControl(
'childGroup',
this.fb.group({
field1: [
'', [Validators.required]
],
etc...
}
);
直到我在父组件的ngAfterViewInit
生命周期钩子中发出请求后尝试并This.form.get('childGroup').patchValue({…})
,这一切都是有效的。它没有修补组,而是抛出一个:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has
changed after it was checked. Previous value: 'ng-valid: false'. Current value:
'ng-valid: true'.
有没有办法让子组件将自己添加到
FormGroup
,而不让父组件设置FormGroup
控件和验证。我们需要在应用程序中以不同的方式和组合重用子组件,因此不想在子组件之外重复FormGroup
声明,但这似乎不起作用。您找到解决方案了吗?