繁体   English   中英

Angular 使用 ComponentFactoryResolver 创建多个组件

[英]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();
}

简要说明:

  • ComponentFactoryResolver 用于为 component.ref 输入属性中指定的组件解析 ComponentFactory。
  • 使用 trimCount 属性将 inputItems 数组切片为较小的大小,并对切片数组中的每个项目执行循环。
  • 在循环中,迭代组件输入的输入属性,并使用 inputKey 和 inputValue 变量为每个输入创建输入绑定。
  • 然后调用 ViewContainerRef 的 createComponent() 方法,使用 inputs 属性传递 ComponentFactory 以及在上一步中创建的输入绑定。

这应该创建组件的多个实例,每个实例都有自己的一组输入绑定,而不是通过引用共享相同的实例数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM