Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Service to dynamically append Angular components to the body
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);
}
}
@kaleem7832

This comment has been minimized.

Copy link

@kaleem7832 kaleem7832 commented Oct 10, 2019

how to use this service?

@caroso1222

This comment has been minimized.

Copy link
Owner Author

@caroso1222 caroso1222 commented Oct 10, 2019

This gist is part of this tutorial: https://medium.com/hackernoon/angular-pro-tip-how-to-dynamically-create-components-in-body-ba200cc289e6. You'll see the instructions on how to use this service over there.

@reed-lawrence

This comment has been minimized.

Copy link

@reed-lawrence reed-lawrence commented Oct 25, 2019

Great code! I made some small modifications to allow for initializing component properties and appending to any html element!

https://gist.github.com/reed-lawrence/1f6b7c328ad3886e60dc2b0adcf75a97

@ha-rc

This comment has been minimized.

Copy link

@ha-rc ha-rc commented Jun 11, 2020

I did it and it work well,
but that does not include the styleUrls - css files.
how can I include them?

@asmaus

This comment has been minimized.

Copy link

@asmaus asmaus commented Nov 12, 2020

It works perfectly the first time!
Thank you very much for the contribution.

@caoyuanqi

This comment has been minimized.

Copy link

@caoyuanqi caoyuanqi commented Dec 18, 2020

I guess you can use this instead

const domElem = componentRef.location.nativeElement;

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