小编use*_*007的帖子

在 Angular 中创建嵌套动态组件

我想知道如何创建嵌套动态组件并维护其父子关系。

例如,我有这样的数据,

- A
--A.1
--A.2
-B
--B.1
-C 
Run Code Online (Sandbox Code Playgroud)

我想创建这样的组件,

<A>
   <A1></A1>
   <A2></A2>
</A>
<B>
   <B1></B1>
</B>
<C></C>
Run Code Online (Sandbox Code Playgroud)

但使用我的代码,我只能创建父组件或子组件。但不是两者兼而有之。

下面是我的代码,

  setRootViewContainerRef(view: ViewContainerRef): void {
    this.rootViewContainer = view;
  }

  createComponent(content: any, type: any) {
 console.log(content);
    if (content.child && content.child.length > 0) {
      content.child.forEach(type => {
        const typeP = this.contentMappings[type.type];
        this.createComponent(type, typeP);
      });
    } else {
      this.renderComp(content,type)
    }
  }

  renderComp(content,type) {
    if (!type) {
      return
    }
    this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
    this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);

    if (this.componentReference.instance.contentOnCreate) {
      this.componentReference.instance.contentOnCreate(content);
    }
  }
Run Code Online (Sandbox Code Playgroud)

通过这段代码,我得到了这个输出。

链接到工作示例StackBlitz

请帮我解决这个问题。 …

javascript typescript angular angular-dynamic-components

3
推荐指数
1
解决办法
3048
查看次数