3

我正在尝试在组件内部单击按钮时动态加载模态窗口组件,DynamicComponentLoader如下所示 -

openUploadDialog() {
  this._loader.loadAsRoot(MyDialog, '#upload-image', this._injector).
    then((c:ComponentRef<MyDialog>) => {
      c.instance.openModal();
    });    
}

MyDialog 组件 -

@ViewChild('dialog') dialog: ElementRef;
 openModal() {   
   if (!this.dialog.nativeElement.showModal) {
     dialogPolyfill.registerDialog(this.dialog.nativeElement);
   }    
   this.dialog.nativeElement.showModal();
 }

但是我收到错误 - Cannot read property 'nativeElement' of undefined。起初我认为对话框 ViewChild 元素当时没有创建,所以我尝试将打开部分移动到ngAfterViewInit事件处理程序。但我注意到,当组件创建时不会调用这些事件处理程序ngOnInit等) ,或者可能只是使用方法,不能肯定地说。我没有尝试过,因为我需要在这个里面共同创建组件。 DynamicComponentLoaderloadAsRootloadNextToLocation

这个问题有什么解决办法吗?

更新

感谢 Günter Zöchbauer 的链接,我做了以下更改 -

@ViewChild('dialog-container', {read: ViewContainerRef}) dialog;

openUploadDialog() {
  this._resolver.resolveComponent(MyDialog)
    .then(fact => this.comp = this.dialog.createComponent(fact))
      .then(res => console.log(res));
}

但是现在我变得this.comp不确定了。有什么我做错了吗?

更新 2

好的,我设法通过像这样重写这个方法来解决这个问题 -

  openUploadDialog() {
    if (this.dialog) {
      this.dialog.instance.openModal();
      return;
    }

    this._resolver.resolveComponent(MyDialog).
      then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([],
          this._container.injector);
        this.dialog = this._container.createComponent(
          factory, null, injector, []);
      });
  }

所以,我认为依赖注入就是这种情况。

4

0 回答 0