如何手动调用这些事件?ngOnInit没有为使用组件工厂解析器注入的组件而被激发



ngOnInit未因使用组件工厂解析器注入的组件而被激发

@ViewChild('target', {
read: ViewContainerRef
}) target;
@Input() step;
@Input() stepinfo;
cmpRef: ComponentRef < any > ;
private isViewInitialized: boolean = false;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private compiler: Compiler,
private cdRef: ChangeDetectorRef
) {}
updateComponent() {
if (!this.isViewInitialized) {
return;
}
if (this.cmpRef) {
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.step);
this.cmpRef = this.target.createComponent(factory)
this.cmpRef.instance.data = this.stepinfo;
// (<InjectComponent>componentRef.instance).data = this.step;
// this.cdRef.detectChanges();
}

经过几次阅读,我知道在这种情况下,我们需要手动调用这些事件。我正在为如何完成而挣扎

使用ComponentFactoryResolver手动创建组件时,必须手动调用在组件上使用的Angular生命周期事件。

由于这些方法在组件上是公共的,所以可以像调用普通方法一样调用它们。在这种情况下,我们想要调用OnInit生命周期事件,因此它如下所示:

updateComponent() {
if (!this.isViewInitialized) {
return;
}
if (this.cmpRef) {
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.step);
this.cmpRef = this.target.createComponent(factory)
this.cmpRef.instance.data = this.stepinfo;
this.cmpRef.instance.ngOnInit(); // <-- this is where the life cycle event is ran
}

相关内容

最新更新