Skip to content

Instantly share code, notes, and snippets.

@reed-lawrence
Forked from caroso1222/dom.service.ts
Last active July 7, 2022 18:37
Show Gist options
  • Save reed-lawrence/1f6b7c328ad3886e60dc2b0adcf75a97 to your computer and use it in GitHub Desktop.
Save reed-lawrence/1f6b7c328ad3886e60dc2b0adcf75a97 to your computer and use it in GitHub Desktop.
Service to dynamically append Angular components to the body
import {
Injectable,
Injector,
ComponentFactoryResolver,
EmbeddedViewRef,
ApplicationRef,
ComponentRef
} from '@angular/core';
@Injectable()
export class DomService {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) { }
createComponent(component: any, componentProps?: object) {
// 1. Create a component reference from the component
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
.create(this.injector);
if (componentProps && typeof componentRef.instance === 'object') {
Object.assign(componentRef.instance as object, componentProps);
}
return componentRef;
}
attachComponent(componentRef: ComponentRef<unknown>, appendTo: Element) {
// 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
appendTo.appendChild(domElem);
return;
}
}
@reed-lawrence
Copy link
Author

Modified to be able to append to any Element reference. Returning the componentRef allows for better controller of the component - for destruction via .destroy() for example

@lehuusonk35
Copy link

How to use this ? Can you give me an introduction ?

@ha-rc
Copy link

ha-rc commented Jun 11, 2020

how to use this service?

@TANK2003
Copy link

it works very well for me, Thanks !

@robertszooba
Copy link

How would you remove an element using this approach?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment