Guest User

Untitled

a guest
Dec 10th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. constructor(
  2. private componentFactoryResolver: ComponentFactoryResolver,
  3. private appRef: ApplicationRef,
  4. private injector: Injector
  5. ) { }
  6.  
  7. appendComponentToBody(component: any) {
  8. // 1. Create a component reference from the component
  9. const componentRef = this.componentFactoryResolver
  10. .resolveComponentFactory(component)
  11. .create(this.injector);
  12.  
  13. // 2. Attach component to the appRef so that it's inside the ng component tree
  14. this.appRef.attachView(componentRef.hostView);
  15.  
  16. // 3. Get DOM element from component
  17. const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
  18. .rootNodes[0] as HTMLElement;
  19.  
  20. // 4. Append DOM element to the body
  21. document.body.appendChild(domElem);
  22.  
  23. // 5. Wait some time and remove it from the component tree and from the DOM
  24. setTimeout(() => {
  25. this.appRef.detachView(componentRef.hostView);
  26. componentRef.destroy();
  27. }, 3000);
  28. }
Add Comment
Please, Sign In to add comment