角动态组件加载-ExpressionChangedAfterItHasBeenCheckedError [英] Angular dynamic component loading - ExpressionChangedAfterItHasBeenCheckedError
问题描述
我需要在运行时动态创建多个组件的实例.
I need to create instances of multiple components dynamically on the run.
我在互联网上找到了几个示例,包括StackOverflow和angular.io页面本身.
I found several examples on the internet, including StackOverflow and angular.io page itself.
但是当我为组件模型分配值时,总是会收到异常ExpressionChangedAfterItHasBeenCheckedError.
But always receiving exception ExpressionChangedAfterItHasBeenCheckedError when I'm assigning a value to the component model.
即使此功能的专用示例也会引发相同的异常: Angular.io文章 柱塞
Even the dedicated example for this functionality throws the same exception: Angular.io article Plunker
错误错误:ExpressionChangedAfterItHasBeenCheckedError:检查表达式后,表达式已更改.上一个值:未定义".当前值:"Bombasto".似乎已在对视图的父级和子级进行脏检查后创建了该视图.它是在变更检测挂钩中创建的吗?
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Bombasto'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?
我应该忽略它还是可以/应该解决它?
Should I just ignore this or it can/should be fixed?
推荐答案
这是因为您正在更改ngAfterViewInit
中的组件状态.参见此处的问题讨论行为.
This is because you are altering component state in ngAfterViewInit
. See the issue here discussing the behavior.
根据您的情况,您可以将初始创建的内容移至ngOnInit
.
In your case you can move the initial creating in ngOnInit
.
ngOnInit() {
this.loadComponent();
this.getAds();
}
https://plnkr.co/edit/vAbkBIqrhpuuWadO4zGD?p=preview
这篇关于角动态组件加载-ExpressionChangedAfterItHasBeenCheckedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!