### File

`projects/commons/src/lib/shared/dom/dom.service.ts`

    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<T> {
        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<T>(component: ComponentType<T>, injector?: PortalInjector): ComponentRef<T> {
            const componentRef: ComponentRef<T> = 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<any>): HTMLElement => {
            return (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
        }
    }

# result-matching ""

# No results matching ""