Is there a way to insert dynamically a component as a child (not a sibling) of a DOM tag in Angular 2?
There are plenty of examples around there to
I was searching for solution for same problem and approved answer not worked for me. But I have found better and much logical solution how to append dynamically created component as child to current host element.
The idea is to use element reference of newly created component and append it to current element ref by using render service. We can get component object via its injector property.
Here is the code:
@Directive({
selector: '[mydirective]'
})
export class MyDirectiveDirective {
constructor(
private cfResolver: ComponentFactoryResolver,
public vcRef: ViewContainerRef,
private renderer: Renderer2
) {}
public appendComponent() {
const factory =
this.cfResolver.resolveComponentFactory(MyDynamicComponent);
const componentRef = this.vcRef.createComponent(factory);
this.renderer.appendChild(
this.vcRef.element.nativeElement,
componentRef.injector.get(MyDynamicComponent).elRef.nativeElement
);
}
}