角嵌套动态组件

时间:2020-05-25 12:34:02

标签: angular angular-directive

我想根据给定的json动态创建组件。第一个级别是TestComponent,它可以具有许多TestLayerComponent。问题在于TestLayerComponent也可以具有许多TestLayerComponents。我用它来动态制作幻灯片推送菜单。如果“图层路径”以欧洲开头,则使用文本“欧洲”创建<li>,如果欧洲具有巴尔干,则使用<ul>巴尔干等在欧洲创建新的<li>

菜单必须看起来like this,但要使用不与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();
}

1 个答案:

答案 0 :(得分:0)

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++;
  }
}