Para crear dinámicamente componentes en Angular +5 me creo un servicio:
import {
ComponentFactoryResolver, Inject, ViewContainerRef,
ApplicationRef, ComponentRef, EmbeddedViewRef,
Injector, Type, Injectable
} from '@angular/core';
@Injectable()
export class ComponentLauncher {
private _componentRef: ComponentRef<any> = null;
constructor(
private aplicationRef: ApplicationRef,
private resolver: ComponentFactoryResolver,
private injector: Injector
) {}
create<T>(component: Type<T>, props: {[key: string]: any} = {}): ComponentRef<T> {
// Prepare factory, reference, component element and component root element
const componentFactory = this.resolver.resolveComponentFactory(component);
const componentRef = componentFactory.create(this.injector);
const componentElement = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
const componentRootElement = (this.aplicationRef.components[0].hostView as EmbeddedViewRef<any>).rootNodes[0] as Element;
// Properties passed to Component
Object.keys(props || {}).forEach(prop => componentRef.instance[prop] = props[prop]);
// Attach & Instance Component
setTimeout(() => {
this.aplicationRef.attachView(componentRef.hostView);
componentRef.onDestroy(() => this.aplicationRef.detachView(componentRef.hostView));
componentRootElement.appendChild(componentElement);
});
return this._componentRef = componentRef;
}
destroy(): void {
if (this._componentRef) {
setTimeout(() => {
this._componentRef.destroy();
this._componentRef = null;
});
}
}
}
Y luego lo utilizo:
const AlertComponent = this.componentLauncher.create(AlertComponent).instance;
// Si es necesario, más adelante lo libero del DOM y de la memoria
this.componentLauncher.destroy();