[英]Angular Create multiple components using ComponentFactoryResolver
我正在尝试使用ComponentFactoryResolver
动态创建组件。
我有一个组件,它有一个@input
保存组件 ref 和组件输入。
问题是当在 DOM 中创建组件时,它们保存了确切的实例数据。
是否可以在没有它们通过引用持有实例 state 的情况下创建组件?
class TrimItemsToPopupListComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() component?: {
ref: ComponentType<unknown>,
inputs: Record<string, unknown>[]
};
constructor(
private resolver: ComponentFactoryResolver,
private cd: ChangeDetectorRef
) {}
ngAfterViewInit(): void {
this.componentVC.clear();
this.inputItems.slice(0, this.trimCount).forEach(() => {
const factory = this.resolver.resolveComponentFactory(this.component.ref);
const componentRef = this.componentVC.createComponent(factory);
this.component.inputs.forEach((cmpInput, index) => {
const inputKey = Object.keys(cmpInput)[0] as string;
// @ts-ignore
componentRef.instance[inputKey] = this.component.inputs[index][inputKey];
});
});
this.cd.detectChanges();
}
你可以试试这个:
class TrimItemsToPopupListComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() component ?: {
ref: ComponentType<unknown>,
inputs: Record<string, unknown>[]
};
constructor(
private resolver: ComponentFactoryResolver,
private cd: ChangeDetectorRef
) { }
ngAfterViewInit(): void
{
this.componentVC.clear();
this.inputItems.slice(0, this.trimCount).forEach(() => {
const factory = this.resolver.resolveComponentFactory(this.component.ref);
this.component.inputs.forEach((cmpInput, index) => {
const inputKey = Object.keys(cmpInput)[0] as string;
const inputValue = this.component.inputs[index][inputKey];
const inputBinding = { [inputKey]: inputValue };
// Pass the input binding as the `inputs` property
const componentRef = this.componentVC.createComponent(factory, undefined, undefined, [inputBinding]);
});
});
this.cd.detectChanges();
}
简要说明:
这应该创建组件的多个实例,每个实例都有自己的一组输入绑定,而不是通过引用共享相同的实例数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.