import { Component, OnInit, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver } from '@angular/core'; @Component({ selector: 'cf-dynamic-component-loader', template: "
", styles: [""] }) export class CfDynamicComponentLoaderComponent { currentComponent = null; @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef; /** *Data for the dynamically loaded component.
*data.component: Component name
*data.inputs: Component input parameters
*data.loadedInstance: reference to ComponentRef of the current component instance * - NOT to pass - it's set by dynalic loader after loading component and can be used to destroy component
*data.id: component ID - to pass if you want it to be set for the specific value, i.e. for ID from storage
*/ @Input() set componentData(data: { component: any, inputs: any, loadedInstance: any, id: string }) { if (!data) { return; } const inputProviders = Object.keys(data.inputs).map(inputName => { return { provide: inputName, useValue: data.inputs[inputName] }; }); const resolvedInputs = ReflectiveInjector.resolve(inputProviders); const injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector); const factory = this.resolver.resolveComponentFactory(data.component); const component = factory.create(injector); this.dynamicComponentContainer.insert(component.hostView); if (this.currentComponent) { this.currentComponent.destroy(); } this.currentComponent = component; // if injected component does not use Injector in his constructor // and does not hard-codes getting its inputs from Injector inputProviders.forEach((next) => { if (! this.currentComponent._component[next.provide]) { this.currentComponent._component[next.provide] = next.useValue; } }); // reset compId for the one from storage if (data.id) { this.currentComponent._component.id = data.id; } // store reference to ComponentRef of the current component instance // in case if user wants to use it later, i.e. to destroy component data.loadedInstance = this.currentComponent; } constructor(private resolver: ComponentFactoryResolver) { } }