[英]Angular dynamic component loading - ExpressionChangedAfterItHasBeenCheckedError
I need to create instances of multiple components dynamically on the run. 我需要在运行时动态创建多个组件的实例。
I found several examples on the internet, including StackOverflow and angular.io page itself. 我在互联网上找到了几个例子,包括StackOverflow和angular.io页面本身。
But always receiving exception ExpressionChangedAfterItHasBeenCheckedError when I'm assigning a value to the component model. 但是当我为组件模型赋值时,总是会收到异常ExpressionChangedAfterItHasBeenCheckedError。
Even the dedicated example for this functionality throws the same exception: Angular.io article Plunker 即使是此功能的专用示例也会引发相同的异常: Angular.io文章 Plunker
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后发生了变化。 Previous value: 'undefined'. 上一个值:'undefined'。 Current value: 'Bombasto'. 当前价值:'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? 我应该忽略这个还是可以/应该修复?
This is because you are altering component state in ngAfterViewInit
. 这是因为您正在改变ngAfterViewInit
组件状态。 See the issue here discussing the behavior. 请参阅此处讨论行为的问题 。
In your case you can move the initial creating in ngOnInit
. 在您的情况下,您可以在ngOnInit
移动初始创建。
ngOnInit() {
this.loadComponent();
this.getAds();
}
https://plnkr.co/edit/vAbkBIqrhpuuWadO4zGD?p=preview https://plnkr.co/edit/vAbkBIqrhpuuWadO4zGD?p=preview
In the more general case 在更一般的情况下
use 采用
this._changeDetectionRef.detectChanges();
at the end of the method that did update to late the component state, 在更新到组件状态后期的方法的最后,
... not forgetting to add ......别忘了补充
private _changeDetectionRef : ChangeDetectorRef
as parameter of the constructor of the Component owning your method. 作为拥有您的方法的Component的构造函数的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.