访问动态创建的输入

Accessing dynamically created inputs

我有以下代码

createPhone(): void {
    const widgetFactory = this._resolver.resolveComponentFactory( PhoneComponent );
    this.componentRef =
        this.container.createComponent( widgetFactory );
    this.componentRef.instance.containerRef = this.container;
  }

在动态输入为created/attached的PoneComponent中,在PhoneComponent的哪个生命周期方法中可以访问this.componentRef.instance.containerRef?

我为每个使用的生命周期方法得到一个未定义的。

谢谢

您可以在除 ngOnChanges 以外的任何生命周期方法中使用它,因为在您的上述代码中,值是在调用任何生命周期方法之前分配的。 ngOnChanges 未被调用,因为动态添加的组件不能有任何绑定。

也不能使用构造函数,因为赋值是在组件构造完成后进行的。

确保 this.container 已定义。

Plunker example