我一直在使用这样的代码在我的应用程序中动态创建组件。这些组件必须支持动态输入。但现在我尝试更新到 Angular 5 并且 ReflectiveInjector 已被弃用。如果有人知道如何帮助我在 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) {
}
}
最佳答案
May this give some clue.
constructor(private renderer: Renderer2,
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver) {
}
private createdDynamicComponent(): void {
const factory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
const createdComponentComponent = this.viewContainerRef.createComponent(factory);
this.renderer.appendChild('element where you want append', createdComponentComponent.location.nativeElement);
}
关于angular - 使用 Angular 5 动态创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573563/