Angular2 - Dynamic components in content received by API

后端 未结 3 633
礼貌的吻别
礼貌的吻别 2021-01-22 17:04

I have a component . The content for this component is received by API and it contains another components .

The question is, how to render the child component. When I pu

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 17:34

    Using other answers and Gunter's hints here is what works for me:

    @Component({
      selector: 'blog-app',
      template: `
      

    Article preview

    ` }) export class BlogAppComponent { @Input() content : string; @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef; constructor (private zone : NgZone, private compiler: Compiler ) { } private addComponent(template: string) { @Component({template: template}) class TemplateComponent {} @NgModule({declarations: [TemplateComponent], imports: [BlogAppModule]}) class TemplateModule {} const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule); const factory = mod.componentFactories.find((comp) => comp.componentType === TemplateComponent ); const component = this.container.createComponent(factory); } ngOnChanges(changes: SimpleChanges) { this.zone.run(() => { this.addComponent(changes['content'].currentValue); }); } }

提交回复
热议问题