In an Angular 7 modal service I am creating a modal Stackblitz.
The modal is simply a DIV added to document as follows:
const modal = document.createElement('div');
modal.classList.add('modal');
modal.appendChild(this.element);
document.body.appendChild(this.modal);
The modal
content (this.element) is a component created dynamically.
What I would like is modal
to be also a Component added dynamically:
- Create modal from a ModalComponent (I think similar to 2);
- Create element component (DONE);
- Add element component as child of modal component;
- Add modal component to document.
Could someone help me with (3) and (4)? Not sure how to do it.
Modal
export class Modal {
protected modal: any = null;
close() {
this.modal.close();
}
}
ModalService
import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector, ComponentRef, ReflectiveInjector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private component: ComponentRef<any>;
private element: any;
private stage: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private application: ApplicationRef, private injector: Injector) { }
open(component: any, data: any): void {
if(this.element)
return;
const injector: Injector = ReflectiveInjector.resolveAndCreate([{ provide: 'modal', useValue: data }]);
this.component = this.componentFactoryResolver.resolveComponentFactory(component).create(injector);
this.component.instance.modal = this;
this.application.attachView(this.component.hostView);
this.element = (this.component.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
const modal = document.createElement('div');
modal.classList.add('modal');
modal.appendChild(this.element);
document.body.appendChild(this.modal);
}
close(): void {
this.application.detachView(this.component.hostView);
this.stage.parentNode.removeChild(this.stage);
this.component.destroy();
this.element = null;
}
}