I've been trying to dynamically create a component and append it to the document tag. I've been having a hard time figuring out how to select the body's ViewContainterRef so I can just append a new component using the ComponentFactoryResolver.
I tried to obtain a reference to the body container using the code below, but it does not work. Does anybody know how to do it? Thanks!
import {
Component,
ComponentRef,
ApplicationRef,
Injector,
Input,
ViewContainerRef,
ComponentFactoryResolver,
ViewChild,
OnInit,
OnDestroy
} from '@angular/core';
import {
ModalComponent
} from './modal.component';
@Component({
selector: 'my-modal'
})
export class MyModalComponent {
private _bodyRef: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver, private app: ApplicationRef) {
// Does not work!
this._bodyRef = app['_rootComponents'][0]['_hostElement'].vcRef;
}
ngOnInit() {
// Calls the factory to crate a brand new instance
let componentFactory = this.resolver.resolveComponentFactory(ModalComponent);
this._bodyRef.createComponent(componentFactory);
}
}