I need to manage the dialog component from a service, so each feature's component can invoke the service to open a screen in a dialog, so below my dialog component which displays a PrimeNG dialog:
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent {
display = true;
title = '';
private componentRef;
@ViewChild('content', { read: ViewContainerRef }) contentRef: ViewContainerRef;
constructor() { }
open(component, componentRef) {
this.componentRef = componentRef;
this.contentRef.createComponent(component);
}
onHide(){
this.componentRef.destroy();
}
}
And its template:
<p-dialog modal="true" [header]="title" [(visible)]="display" (onHide)="onHide()">
<ng-template #content></ng-template>
</p-dialog>
Below my service:
@Injectable()
export class DialogService {
rootViewContainer;
constructor(private factoryResolver: ComponentFactoryResolver) { }
setRootViewContainerRef(viewContainerRef) {
this.rootViewContainer = viewContainerRef
}
public open(component) {
let dialogFactory = this.factoryResolver.resolveComponentFactory(DialogComponent);
let dialogRef = this.rootViewContainer.createComponent(dialogFactory);
let componentFactory = this.factoryResolver.resolveComponentFactory(component);
dialogRef.instance.open(componentFactory, dialogRef);
}
}
I can call "setRootViewContainerRef" of the service using any component's container reference ("ViewContainerRef"), I need to get the reference of the body container so all my dialogs will be inserted into the body. How can I get the reference to the body element ?
Thanks