angular attach component to body code example

Example: angular attach component to body

import {
    Injectable,
    Injector,
    ComponentFactoryResolver,
    EmbeddedViewRef,
    ApplicationRef,
    ComponentRef
} from '@angular/core';
import { ModalComponent } from './modal.component';
@Injectable({
  providedIn: 'root'
})
export class ModalService {
  constructor(
      private componentFactoryResolver: ComponentFactoryResolver,
      private appRef: ApplicationRef,
      private injector: Injector
  ) { }
  appendComponentToBody(component: any) {
    // Create a component reference from the incoming component 
    let componentRef = this.componentFactoryResolver
      .resolveComponentFactory(component)
      .create(this.injector);
    // Attach incoming component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(componentRef.hostView);
    // Get DOM element from incoming component
    let contentElem = (componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;
    // Create a component reference from the service component 
    let componentRefer = this.componentFactoryResolver
      .resolveComponentFactory(ModalComponent)
      .create(this.injector);
    // Attach component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(componentRefer.hostView);
    // Get DOM element from service component
    let domElem = (componentRefer.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;
    // Append DOM element to the body
    document.body.appendChild(domElem);
    // Add incoming component to modal component
    domElem.querySelector('#Modal').appendChild(contentElem);
  }
}