在加载我的父组件时,我正在使用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();**
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我不得不使用detectChanges()作为上述函数的最后一行,因为没有它我得到错误:
ParentComponent.html:1错误错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改.上一个值:'ng-pristine:true'.当前值:'ng-pristine:false'.
我想我明白为什么会这样.Angular开始检查父组件,然后,开始检查子组件,然后,在子组件上,子组件,在writeValue函数上更改父组件的表单状态.
我对使用detectChanges()感到不舒服.有没有办法做别的事情?是否必须使用父组件和子组件,每个组件都有formGroup,子组件是父formgroup formControl之一?
小智 0
Angular 应用程序状态更改可能来自:
ChangeDetectorRef但是,当您使用 Control Value Accessor 写入值时,您需要使用和告诉 Angular update 更改detectChanges()
你应该看看Pascal Precht 的文章Whonotents Angular这一部分
| 归档时间: |
|
| 查看次数: |
2028 次 |
| 最近记录: |