【发布时间】:2021-12-21 21:28:21
【问题描述】:
我正在开发一个 Angular 13 项目,我需要渲染动态组件。组件模板和 biz 逻辑作为字符串来自服务器端。我读到您不能在 Angular 13 中动态创建模板,因为任何组件都必须在构建时由 Angular 编译,并且 Angular 应用程序不附带 JIT 编译器。
这仅适用于我允许客户构建自定义仪表板的应用程序的一部分。
在 Angular 12 中可以做到这一点,但在 Angular 13 中,编译器服务不再公开。
在 Angular 12 中工作的代码:
模板:
<div>
<ng-container *ngComponentOutlet="component"></ng-container>
</div>
组件:
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
}
}
我想知道您是否需要在 Angular 13 或更高版本中使用一组不同的 API 才能做到这一点。有人做过吗?
【问题讨论】:
-
我很好奇是否有一种简单的方法来实现这一点,但我担心将字符串编译为 Angular 模板所需的代码远非微不足道。如果可以,您应该尝试将组件作为配置对象并避免 JIT。如果你不能,那么我很好奇如何做到这一点。您正在描述一个插件架构(“插件”是在应用程序构建之后编译的)并且 AFAICT 它是一个 Angular 圣杯。
-
感谢您的评论@A.Chiesa。我降级到 Angular 12 并且能够使用编译 API。我遵循了一个项目示例:github.com/johncrim/angular-dynamic-styleguide。我的问题仍然悬而未决。 Angular 13 可以做类似的事情吗?
-
在 angular.json 中设置 "aot": false & "production": { "buildOptimizer": false ...}
标签: javascript angular dynamic