首页 > 解决方案 > Angular 嵌套动态组件

问题描述

我想从给定的 json 动态创建组件。第一层是TestComponent,可以有很多TestLayerComponent。问题是TestLayerComponent 也可以有很多TestLayerComponent。我用它来动态制作幻灯片推送菜单。如果图层路径以 Europe 开头<li>,则使用文本 Europe 创建,如果 Europe 有 Balkans,则使用 Balkans<ul>在欧洲创建新的<li>等等。

菜单必须看起来像这样,但使用不使用 DOM 的组件实现。

    [{
  Username:"",
  Password:"",
  Maps:[
    {
    Name:"",
    Title:"",
    Layers:[
       id:""
       path:"Europe/Balkans/Greece"
     ]
   },

    {
    Name:"",
    Title:"",
    Layers:[
       id:""
       path:"Europe/Balkans/Romania"
     ]
   },
  {
    Name:"",
    Title:"",
    Layers:[
       id:""
       path:"Asia/China"
     ]
   },
  ]

}
]

这是我尝试但仍仅显示最后一个组件的代码。

for (const map of maps) {
  mapViewContainerRef.clear();
  let mapRow = mapViewContainerRef.createComponent(mapFactory);
  mapRow.instance.maps = map;
  for (const layer of map.layers) {
    mapFactory = this.menuFactory.resolveComponentFactory(TestLayerComponent);
    mapViewContainerRef.clear();
    mapViewContainerRef.createComponent(mapFactory);
    mapRow = mapViewContainerRef.createComponent(mapFactory);
    mapRow.instance.layers = layer;
  }
  mapRow.destroy();
}

标签: angularangular-directive

解决方案


for (const map of maps) {
  mapViewContainerRef.clear();
  let mapRow = mapViewContainerRef.createComponent(mapFactory);
  let index = 1;
  mapRow.instance.maps = map;
  for (const layer of map.layers) {
    mapFactory = this.menuFactory.resolveComponentFactory(TestLayerComponent);
    mapRow = mapViewContainerRef.createComponent(mapFactory, index);
    mapRow.instance.layers = layer;
    index++;
  }
}

推荐阅读