首页 > 解决方案 > Angular:如何使用继承来扩展动态组件?

问题描述

我用这样的实例创建了一个动态组件,组件的名称是dynamicComponent1

createComponent() {
    const componentType = this.getComponentType(this.type);
    const factory = this.componentFactoryResolver.resolveComponentFactory(componentType);
    this.componentRef = this.container.createComponent(factory);
    const instance = <Data>this.componentRef.instance;
    instance.data = this.data
  }

像这样的课程:

export class Data{ data: any }

让我们假设这些数据有一个 ID。所以我尝试在下一个组件中扩展数据类并且是 DynamicComponent1 的一个实例。这个组件也创建了动态组件。我尝试从this.data更改实例ID。然后它的改变不是 instance.data.id 而是完整的数据被改变。

来自 DynamicComponent2 的代码:

@ViewChildren() 多个是 ViewContainerRef 的 QueryList

所以我们假设 data 的长度为 2 并且 data.id 是 {list,test} 并且倍数长度太 2

for (let i = 0; i < this.multiple.toArray().length; i++) {
    const target = this.multiple.toArray()[i];
    for (let j = 0; j < this.data.length; j++) {
        const componentType = this.getComponentType(randomName + '_' + randomName);
        if (componentType) {
            const factory = this.componentFactoryResolver.resolveComponentFactory(componentType);
            const cmpRef = target.createComponent(factory);
            const instance = cmpRef.instance as Data;
            this.logger.log('info', cmpRef.instance); // the first data.id is list0011 the second data.id is test0011
            instance.data.id = data.id + i;
            this.logger.log('info', cmpRef.instance); // data.id is list0011
            this.logger.log('info', instance.data.id); // is list0 change after the loop to list0011 and test0011
            this.logger.log('info', data.id); // is list0011


        }
    }
}

所以我的问题是,如何在不更改完整 data.id 的情况下更改此 instance.data.id?为什么 cmpRef.instance 在我初始化它们之前就已经知道 instance.data.id 了?我不知道为什么,它的行为如此令人毛骨悚然。我真的希望你能帮助我,我真的完成了。抱歉这段代码,我无法发送原始代码,所以我必须重写它。

如果您需要更多,我会尽力解释得更好。

我在尝试什么?

  1. 交接服务
  2. 创建一个具有 data.id 的 const
  3. 尝试在 instance.data.id 之后更改 data.id

标签: angulardynamiccomponentsangular5angular-dynamic-components

解决方案


推荐阅读