构建 cdk modal - ngOnInit 未被触发且未传递任何数据

Building cdk modal - ngOnInit is not triggered and no data is passed

我正在尝试构建仅依赖于 CDKmodals 库。 使用服务打开模式,我通过 entryComponent 以模式呈现它。

示例如下:https://stackblitz.com/edit/angular-ofzpks?file=src%2Fapp%2Fmodal.component.ts

在模态本身中,我正在使用工厂创建组件:

const compRef = this.componentFactoryResolver.resolveComponentFactory<any>(this.modalContentComponent);
const componentRef = this.modalContainer.createComponent(compRef);

我有两个问题:

  1. 我必须手动触发componentRef.instance.ngOnInit();
  2. 我将一些数据传递给该组件:componentRef.instance.name = this.data.name; 但组件从未呈现它

在你的 modal.component.ts 中,使用 ngOnInit 而不是 ngAfterViewInit:

ngOnInit() {
  const compRef = this.componentFactoryResolver.resolveComponentFactory<any>(this.modalContentComponent);
  const componentRef = this.modalContainer.createComponent(compRef);
  componentRef.instance.name = this.data.name;
}

Updated StackBlitz


这样做意味着 ngDoCheck 将 运行 并检测自 ngDoCheck 运行 之后 ngOnInit 之后的变化。