How to add a component into a elementref?
You might be able to use Renderer2
export class AppComponent {
@ViewChild('addButton')
private animateThis: ElementRef;
constructor(private renderer: Renderer2) {}
addBtn() {
const button = this.renderer.createElement('button');
const buttonText = this.renderer.createText('This is a button');
this.renderer.appendChild(button, buttonText);
this.renderer.appendChild(this.animateThis.nativeElement, button);
}
}
More examples
In one of my projects, I achieved something similar to your requirement this way. Let me know if it helps?
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector,
private appRef: ApplicationRef) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); // Your dynamic component will replace DynamicComponent
const componentRef = componentFactory.create(this.injector);
this.appRef.attachView(componentRef.hostView);
const domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
const element: HTMLElement = document.createElement('div');
element.appendChild(domElem); // Component needs to be added here
document.body.appendChild(element);
}
This way you will have reference to your dynamic component as componentRef