I have been using code like this to dynamically create components in my application. These components must support dynamic inputs. But now I tried updating to Angular 5 and ReflectiveInjector is deprecated. I would be very grateful if anyone would know how to help me to reuse this with Angular 5...
import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver} from '@angular/core';
import {
AComponent,
BComponent,
CComponent
} from './';
@Component({
selector: 'dynamic-component',
entryComponents: [
AComponent,
BComponent,
CComponent
],
template: `
<div #dynamicComponentContainer></div>
`
})
export class DynamicComponent {
currentComponent = null;
@ViewChild('dynamicPriceItemComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
@Input() set componentData( data: { component: any, inputs: any }) {
if (!data) {
return;
}
let inputProviders = Object.keys(data.inputs).map((inputName) => {
return { provide: inputName, useValue: data.inputs[inputName] };
});
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicPriceItemComponentContainer.parentInjector);
let factory = this.resolver.resolveComponentFactory(data.component);
let component = factory.create(injector);
this.dynamicComponentContainer.insert(component.hostView);
if (this.currentComponent) {
this.currentComponent.destroy();
}
this.currentComponent = component;
}
constructor(private resolver: ComponentFactoryResolver) {
}
}