根据此example,我尝试通过*ngFor
创建多个动态组件,
并通过.instance
绑定数据。但是我发现绑定数据时触发了错误ExpressionChangedAfterItHasBeenCheckedErro
。
例如来自example的
ngAfterViewInit() {
const dashWidgetsConf = this.widgetConfigs();
const widgetComponents = this.widgetComponents();
for (let i = 0; i < this.widgetTargets.toArray().length; i++) {
let conf = dashWidgetsConf[i];
let component = widgetComponents[conf.id];
if(component) {
let target = this.widgetTargets.toArray()[i];
let widgetComponent = this.componentFactoryResolver.resolveComponentFactory(component);
let cmpRef: any = target.createComponent(widgetComponent);
if (cmpRef.instance.hasOwnProperty('title')) {
cmpRef.instance.title = conf.title; //bind title variable
}
}
}
}
动态组件:
1.component.ts:
export class Component implements OnInit {
title: any; // define title variable for instance tilte variable
constructor() { }
ngOnInit() {}
}
component.html:
<div>{{title}}<div>
hasOwnProperty
,if(cmpRef.instance.hasOwnProperty('title'))
:
当我删除此判断公式时,数据将绑定,但是无论我是否绑定此判断,都会触发ExpressionChangedAfterItHasBeenCheckedErro
错误。
错误消息:
未设置hasOwnProperty
:
ExpressionChangedAfterItHaHasBeenCheckedError:检查表达式后,表达式已更改。上一个值:“ null:未定义”。当前值:“ null:testtitlevalue”。似乎已在对其父级和子级进行脏检查后创建了该视图。它是在变更检测挂钩中创建的吗?
设置hasOwnProperty
:
ExpressionChangedAfterItHaHasBeenCheckedError:检查表达式后,表达式已更改。上一个值:“ null:未定义”。当前值:“ null:未定义”。似乎已在对其父级和子级进行脏检查后创建了该视图。它是在变更检测挂钩中创建的吗?