Я хочу знать, как создавать вложенные динамические компоненты и поддерживать их отношения между родительскими и дочерними элементами.
Например, у меня есть такие данные,
- A
--A.1
--A.2
-B
--B.1
-C
Я хотел создать такой компонент,
<A>
<A1></A1>
<A2></A2>
</A>
<B>
<B1></B1>
</B>
<C></C>
Но с моим кодом я мог создать только родительский компонент или дочерний компонент. Но не то и другое вместе.
Ниже мой код,
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);
}
}
С помощью этого кода я получаю такой вывод.
Ссылка на рабочий пример, StackBlitz
Пожалуйста, помогите мне решить эту проблему.
Обновлено.
Даже после добавления viewChild
он все равно бросает viewchild not defined
.
Обратитесь к этому изображению. В component.instance я не вижу дочерний элемент представления.
Обновленная ссылка stackblitz https://stackblitz.com/edit/angular-dynamic-new-mepwch?file=src/app/content/a/a.component.ts