Skip to content

Instantly share code, notes, and snippets.

@achrefabdennebi
Forked from caroso1222/dom.service.ts
Created February 23, 2021 11:15
Show Gist options
  • Select an option

  • Save achrefabdennebi/73c3eb11d00c6ec1be22c404e155d078 to your computer and use it in GitHub Desktop.

Select an option

Save achrefabdennebi/73c3eb11d00c6ec1be22c404e155d078 to your computer and use it in GitHub Desktop.

Revisions

  1. @caroso1222 caroso1222 revised this gist Jun 24, 2017. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion dom.service.ts
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,6 @@ import {
    ApplicationRef
    } from '@angular/core';


    @Injectable()
    export class DomService {

  2. @caroso1222 caroso1222 created this gist Jun 24, 2017.
    41 changes: 41 additions & 0 deletions dom.service.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    import {
    Injectable,
    Injector,
    ComponentFactoryResolver,
    EmbeddedViewRef,
    ApplicationRef
    } from '@angular/core';


    @Injectable()
    export class DomService {

    constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private appRef: ApplicationRef,
    private injector: Injector
    ) { }

    appendComponentToBody(component: any) {
    // 1. Create a component reference from the component
    const componentRef = this.componentFactoryResolver
    .resolveComponentFactory(component)
    .create(this.injector);

    // 2. Attach component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(componentRef.hostView);

    // 3. Get DOM element from component
    const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
    .rootNodes[0] as HTMLElement;

    // 4. Append DOM element to the body
    document.body.appendChild(domElem);

    // 5. Wait some time and remove it from the component tree and from the DOM
    setTimeout(() => {
    this.appRef.detachView(componentRef.hostView);
    componentRef.destroy();
    }, 3000);
    }
    }