Insert dynamic Angular 4.x content with known/declared components

那年仲夏 提交于 2019-12-05 04:36:45

This is very possible, actually...

Angular's ApplicationRef has an attachView() method that will keep track of a new component reference. That component reference can then be inserted anywhere just like a regular component.

Here's a pseudo-code example:

// create a componentRef
const componentFactory = ComponentFactoryResolver.resolveComponentFactory(AngularComponent);
const componentRef = componentFactory.create(Injector);

// attach the componentRef to the angular ApplicationRef
ApplicationRef.attachView(componentRef.hostView);

// insert the root element of the new componentRef into any DOM node
const componentRoot: HTMLElement = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0];
const node = document.getElementById('insertionPoint'); 
Renderer2.insertBefore(node.parentNode, componentRoot, node);

// don't forget to destroy the component when you're done with it
ApplicationRef.detachView(componentRef.hostView);
componentRef.destroy();

Better explanation here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!