I'm trying to created nested dynamic components based on json response.
public content={type:'paragraph',depth:1,text:'Root',entityRanges:[{type:'LINK',offset:83,length:16,data:{target:'_self',url:'/index.htm'}}],embbeded:[{type:'text',text:'This is Text component'}]}
So in the above structure, it as type paragraph so the ParagraphComponent need to render first.
It as an array object embbeded, in this array I wanted to render TextComponent.
So the final output should be like this,
<paraComp><p><textComp>This is Text component</textComp></p></paraComp>
Below is what I tried,
Main Component
export class AppComponent implements OnInit {
@ViewChild('container', { read: ViewContainerRef })
public target: ViewContainerRef;
public content = { type: 'paragraph', depth: 1, text: 'Root', entityRanges: [{ type: 'LINK', offset: 83, length: 16, data: { target: '_self', url: '/index.htm' } }], embbeded: [{ type: 'text', text: 'This is Text component' }] }
constructor(private createDynamicComponentService: CreateDynamicComponentService) { }
ngOnInit() {
this.createDynamicComponentService.createComponent(this.content, this.target);
}
}
Main HTML
<ng-container #container></ng-container>
createDynamicComponentService
export class CreateDynamicComponentService {
private rootViewContainer: ViewContainerRef;
private componentFactory: ComponentFactory<any>;
private componentReference;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
@Inject(CONTENT_MAPPINGS) private contentMappings: any
) { }
setRootViewContainerRef(view: ViewContainerRef): void {
this.rootViewContainer = view;
}
createComponent(content: any, container: ViewContainerRef) {
const type = this.contentMappings[content.type];
console.log(type);
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
}
Link to Project https://stackblitz.com/edit/angular-dynamic-new?file=src/app/app.component.ts
I took reference from this https://github.com/sparkles-dev/ng-content-driven-angular/blob/master/src/app/reactive-content/content-host/content-host.component.ts
Based on it only I've created my project. But not able to make it work.
Please help.