简体   繁体   English

如何在 Angular 13 或更高版本中渲染动态组件

[英]How to render dynamic components in Angular 13 or higher

I'm working on an Angular 13 project, and I need to render dynamic components.我正在做一个 Angular 13 项目,我需要渲染动态组件。 The component template and the biz logic come from the server-side as a string.组件模板和业务逻辑作为字符串来自服务器端。 I read that you can't create templates dynamically in Angular 13, as any component must be compiled by Angular at build time, and Angular apps do not ship with the JIT compiler.我读到您不能在 Angular 13 中动态创建模板,因为任何组件都必须在构建时由 Angular 编译,并且 Angular 应用程序不附带 JIT 编译器。

This is only for one part of the application where I allow customers to build their custom dashboards.这仅适用于我允许客户构建其自定义仪表板的应用程序的一部分。

It was possible to do that in Angular 12, but in Angular 13 the compiler service is no longer exposed.在 Angular 12 中可以这样做,但在 Angular 13 中,编译器服务不再公开。

Code working in Angular 12:在 Angular 12 工作的代码:

Template:模板:

<div>
   <ng-container *ngComponentOutlet="component"></ng-container>
</div>

Component:成分:

import { Compiler, Component, NgModule, OnInit } from '@angular/core'
    @Component({
       selector: 'my-lab',
       templateUrl: './lab.component.html',
       styleUrls: ['./lab.component.scss'],
    })
        export class LabComponent implements OnInit {
           component: any
           constructor(private compiler: Compiler) {}
        
           async ngOnInit() {
              const componentClass = class {
                 public testing = {
                    name: 'yago',
                 }
              }
              const imports = (this.component = await this.compile({
                 template: `<div>Testing here {{ testing | json}}</div>`,
                 componentClass,
                 imports: [CommonsModule],
              }))
           }
        
           async compile(input: any) {
              const { template, componentClass, imports } = input
              const templateCompoment = Component({ template })(componentClass)
        
              const module = NgModule({
                 declarations: [templateCompoment],
                 exports: [templateCompoment],
                 imports: [...imports],
              })(class {})
        
              const compiledModule = await this.compiler.compileModuleAndAllComponentsAsync(module)
              return templateCompoment
           }
        } 

I wonder if you need to use a different set of APIs in Angular 13 or higher to be able to do this.我想知道您是否需要在 Angular 13 或更高版本中使用一组不同的 API 才能执行此操作。 Has anyone done this?有没有人这样做过?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM