Advertisement
Guest User

Untitled

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