Angular中的动态多级组件渲染

问题描述 投票:1回答:1

我们能够在读取json数据时动态构建角度app(版本4.3.6),其中应用程序树结构仅包含一个级别的子级。我们正在使用ComponentResolverFactory这样做。

我们想对嵌套的子项进行相同的尝试,其中一个组件中有多个子组件,而一些子组件可以有更多的子组件。

Json数据结构类似于以下结构。

var config = {
  components: [
    {
      type: "tab-group", //name of the component, with this name we can find out the actual Component class.
      data: {},
      children: [ //These are the children of "tab-group" component
        {
          type: "tab", //First child of the "tab-group" component.
          data: { //This data needs to be provided to the component when we add it to the View
            header:'...'
          },
          children: [
            {
              type: "text-input",
              data: {
               name:'...',
               label:'...',
               ...
              }
            },
             {
              type: "select",
              data: {
               name:'...',
               label:'...',
               ...
              }
            }
          ]
        }
      ]
    }
  ]
};
angular
1个回答
0
投票

我最近这样做了,您可以使用此代码片段为您的方案进行一些调整:

addDynamicComponent(comp, viewContainerRef) {

    const factory = this.factoryResolver.resolveComponentFactory(comp);
    const component = factory.create(viewContainerRef.parentInjector);

    viewContainerRef.insert(component.hostView);

    return component;
  }

ngOnInit() {
  this.loadRecursively(this.config.components);
}

load(type: string): Promise<any> {

  // Swap the path for your app structure, this will fetch the component to use
  return System.import(`../${type}/${type}.component`)
    .catch((err) => {
      console.log(err);
    }
  );
}

 loadRecursively(components, view) {

    for (const component of components) {

      this.load(component.type).then((loadedData) => {

        const component = loadedData[component.componentName];
        const loadedComponent: any = this.addDynamicComponent(component, view);

        // Swap ._id for some unique identifier for the component
        this.instances[component._id] = loadedComponent.instance;

        if (component.children.length) {
          this.loadRecursively(component.children, loadedComponent.instance.viewContainerRef);
        }
      });
    }
  }

编辑:

<ng-template #dynamic></ng-template>

@ViewChild('dynamic', {read: ViewContainerRef}) viewContainerRef: ViewContainerRef;
© www.soinside.com 2019 - 2024. All rights reserved.