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.