import { ComponentFactoryResolver, ComponentRef, Directive, Type, ViewContainerRef, } from '@angular/core'; @Directive({ selector: '[dynamic-component-host-directive]', }) export class DynamicComponentHostDirective { constructor( private _componentFactoryResolver: ComponentFactoryResolver, private _viewContainerRef: ViewContainerRef, ) {} public renderComponent( componentClass: Type, ): ComponentRef { const componentFactory = this._componentFactoryResolver.resolveComponentFactory( componentClass, ); this._viewContainerRef.clear(); const componentRef = this._viewContainerRef.createComponent( componentFactory, ); this._viewContainerRef.element.nativeElement.innerHTML = ''; this._viewContainerRef.element.nativeElement.appendChild( componentRef.location.nativeElement, ); return componentRef; } }