我在运行时创建 Angular 代码,特别是,我使用 SVG 库来创建包含 Angular 代码指令的矢量图形,(click)='myMethod()'
这些指令反过来又调用我在 SVG 封闭组件中静态定义的方法。在运行时生成,我需要编译创建的模板并将其添加到组件中。我当时在这篇非常麻烦的帖子的帮助下使用 Angular 3 实现了这样的代码。我尝试在 Angular 8 应用程序中复制旧代码:
private addComponent(template: string) {
@Component({template: template + ' <div #target></div>'})
class TemplateComponent {
@ViewChild('target', {static: false, read: ViewContainerRef}) public target;
constructor() {
}
public myMethod() {
// do something
}
}
@NgModule({declarations: [TemplateComponent]})
class TemplateModule {
@ViewChild('target', {static: false, read: ViewContainerRef}) public target;
}
// ERROR in next line:
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = mod.componentFactories.find((comp) =>
comp.componentType === TemplateComponent
);
this.container.createComponent(factory);
}
现在失败了
ERROR 错误:在 Compiler._throwError (core.js:38932) 处未加载运行时编译器
一方面,我不知道为什么会发生该错误。我在互联网上找到的所有内容都是关于延迟模块加载中的关键函数语法。另一方面,我想知道,如果以后有五个 Angular 主要版本,还有其他方法可以做到这一点。我读过关于Portals的文章,但它似乎是关于动态加载静态模板,而不是动态生成的未编译模板。期待有人指出我正确的方向。
Post Scriptum:为可以在 AoT 模式下提供针对 Angular v9 的基本运行代码片段的人添加一个赏金。它必须包含一个运行时编译的模板(例如,来自一个字符串变量),该模板包含相关组件中的方法调用。