import { ApplicationRef, ComponentFactoryResolver, ComponentRef, EmbeddedViewRef, Injectable, Injector } from '@angular/core'; import { PortalInjector } from '../portal/portal-injector'; import { OverlayContainer } from '../overlay/overlay-container'; export interface ComponentType { new(...args: any[]): T; } @Injectable() export class DomService { constructor( private readonly injector: Injector, private readonly appRef: ApplicationRef, private readonly overlayContainer: OverlayContainer, private readonly componentFactoryResolver: ComponentFactoryResolver, ) {} public attachComponentPortal(component: ComponentType, injector?: PortalInjector): ComponentRef { const componentRef: ComponentRef = this.componentFactoryResolver .resolveComponentFactory(component) .create(injector ? injector : this.injector); this.appRef.attachView(componentRef.hostView); this.overlayContainer.getContainerElement().appendChild(this.getComponentRootNode(componentRef)); return componentRef; } private readonly getComponentRootNode = (componentRef: ComponentRef): HTMLElement => { return (componentRef.hostView as EmbeddedViewRef).rootNodes[0] as HTMLElement; } }