我正在尝试创建基于json响应的嵌套动态组件。
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'}]}
因此,在上面的结构中,它是paragraph
类型,因此需要首先呈现ParagraphComponent
。
它是一个数组对象embbeded
,在这个数组中我想渲染TextComponent
。
所以最终的输出应该是这样的,
<paraComp><p><textComp>This is Text component</textComp></p></paraComp>
下面是我尝试过的内容,
主组件
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);
}
}
主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);
}
}
链接到项目https://stackblitz.com/edit/angular-dynamic-new?file=src/app/app.component.ts
仅基于此,我已经创建了我的项目。但不能让它工作。
请帮帮忙。
https://stackoverflow.com/questions/56281422
复制相似问题