Can you help me figure out how to create nested dynamic components while maintaining the parent-child relationship?
For instance, if I have data structured like this:
- A
--A.1
--A.2
-B
--B.1
-C
I want to build components that reflect this structure, such as:
<A>
<A1></A1>
<A2></A2>
</A>
<B>
<B1></B1>
</B>
<C></C>
However, my code only allows me to create either a parent component or a child component, but not both at the same time.
This is the snippet of my current code:
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);
}
}
When running this code, I encounter an issue where I can't successfully create both parents and child elements simultaneously.
If you'd like to see a working example, please visit StackBlitz.
I would greatly appreciate your assistance in resolving this matter.
Update:
Even after incorporating the ViewChild
, I'm still facing the error message ViewChild not defined
.
Please refer to this image which shows that the ViewChild element is not visible within the component.instance.
https://i.sstatic.net/waGp9.png
Here is the updated link to StackBlitz for further reference: https://stackblitz.com/edit/angular-dynamic-new-mepwch?file=src/app/content/a/a.component.ts