3

I'm trying to dynamically load modal window component on button click inside the component with DynamicComponentLoader like this -

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

MyDialog component -

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

However I'm getting error - Cannot read property 'nativeElement' of undefined. At first I thought that dialog ViewChild element was not created at that point, so I tried to move the opening part to ngAfterViewInit event handler. But I noticed, that those event handlers(ngOnInit, etc.) are not called when component created with DynamicComponentLoader or maybe it's only with loadAsRoot method, can't say for sure. I haven't tried loadNextToLocation since I need co create component inside this one.

Is there any solution to this problem?

Update

Thanks to Günter Zöchbauer's link, I made the following changes -

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

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

However now I'm getting this.comp to be undefined. Is there anything I'm doing wrong?

Update 2

Okay, I managed to resolve this by rewriting this method like this -

  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, []);
      });
  }

So, I think that dependency injection was the case.

renchan
  • 519
  • 5
  • 24
  • `const injector = ReflectiveInjector.fromResolvedProviders([], this._container.injector);` creates a new injector that has no providers. I think just passing `null` instead of `injector` or omitting all parameters after `factory` achieve the same or a better result. – Günter Zöchbauer Jun 06 '16 at 10:58
  • Hm, strange... whenever I try to pass null instead of `injector` or omit all of the params after factory I'm getting `Error: DI Exception at NoProviderError.BaseException` – renchan Jun 06 '16 at 11:18
  • Weird. See http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 for an example of mine. – Günter Zöchbauer Jun 06 '16 at 11:21

0 Answers0