【发布时间】:2018-08-02 01:51:47
【问题描述】:
在加载我的 父 组件时,我正在使用 patchValue 更新该(父)组件的表单。
在该表单组件中,我的子 ControlValueAccessor 组件也有一个表单组。因此,在我的 writeValue 函数中,我正在更新子组件关于从父组件 patchValue 传递的值。
我的 writeValue 函数如下所示:
writeValue(value: CountryAndCity): void {
if (value != null && value.country && value.city) {
this.isDefaultValueDefined = true;
this.form.patchValue({country: value.country});
this.form.patchValue({city: value.city});
**this.cdRef.detectChanges();**
}
}
如您所见,我必须使用 detectChanges() 作为上述函数的最后一行,因为没有它我会收到错误消息:
ParentComponent.html:1 ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ng-pristine: true'。当前值:'ng-pristine: false'。
我想我明白为什么会这样。 Angular 开始检查父组件,然后,开始检查子组件,然后,在子组件上,在子组件上,在 writeValue 函数上更改父组件的表单状态。
我对使用 detectChanges() 感到不舒服。有没有办法做其他事情?使用父组件和子组件时是否必须每个组件都有formGroup,并且子组件是父formgroup formControl之一?
【问题讨论】:
-
您好,您的问题解决了吗?
标签: angular