Skip to content

Instantly share code, notes, and snippets.

@lucianmachado
Created April 15, 2021 00:20
Show Gist options
  • Save lucianmachado/e5f56323703589e178e55e3593d3e69b to your computer and use it in GitHub Desktop.
Save lucianmachado/e5f56323703589e178e55e3593d3e69b to your computer and use it in GitHub Desktop.
Inject angular component by service
import {
ApplicationRef,
ComponentFactoryResolver,
ComponentRef,
EmbeddedViewRef,
Injectable,
Injector
} from '@angular/core';
@Injectable()
export class ComponentInjectorService {
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);
return componentRef;
}
removeComponent(componentRef: ComponentRef<any>) {
componentRef.destroy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment