我正在尝试基于 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>
创建动态组件服务
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
仅基于它,我创建了我的项目。但无法使其工作。
请帮忙。