我们能够在读取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:'...',
...
}
}
]
}
]
}
]
};
答案 0 :(得分: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;