如何手动调用这些事件?使用组件工厂解析程序注入的组件没有触发ngOnInit?

时间:2018-11-08 20:15:30

标签: angular angular6

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();
}
  

在读了几本书之后我才知道我们需要   手动调用这些事件。正在努力做到这一点

1 个答案:

答案 0 :(得分:2)

使用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
}