在Angular 5和AOT-Build中使用@angular编译器时出错 [英] Error while using @angular compiler in Angular 5 and AOT-Build
问题描述
我正在使用Angular编译器在运行时编译组件。这段代码可以正常工作,但是如果我想使用AOT-Prerendering组件将无法正常工作,因为Angular不会在AOT-Build中加载编译器。
i am using the Angular Compiler to compile components in runtime. This Code works fine, but if I want to use AOT-Prerendering the Component wont work, because Angular does not load the Compiler in AOT-Build.
我已阅读关于一些在Angular5 +中不再可用的解决方法。
您对此问题有任何解决方案吗?
I've read about some Workarounds that wont Work in Angular5+ anymore. Do you have any solutions for this problem?
最诚挚的问候
export class RuntimeCompilerComponent {
template: string = "";
@ViewChild('dynamicComponent', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private compiler: Compiler) { }
//Ruft die addComponent Methode auf
createComponent() {
this.addComponent(this.template, null);
}
// Komponente wird dynamisch erzeugt und geladen
// Sollten sich die properties ändern muss ggf. die Changedetection manuell aufgerufen werden.
private addComponent(template: string, properties: any = {}) {
@Component({ template })
class TemplateComponent { }
@NgModule({
imports: [
AppModule,
CommonModule,
ReactiveFormsModule,
FormsModule,
BrowserModule,
], declarations: [TemplateComponent]
})
class TemplateModule { }
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = mod.componentFactories.find((comp) =>
comp.componentType === TemplateComponent
);
const component = this.container.createComponent(factory);
Object.assign(component.instance, properties);
}
}
推荐答案
您可以使用以下方法技巧。去年,我遇到了同样的问题,并且能够找到解决方法。我在样式指南中使用了动态生成的角度分量。这是一个工作示例,可在Angular 7中使用AOT编译:
You can make this work with a few tricks. I ran into the same problem last year, and was able to find a fix. I was using dynamically generated angular components in my style-guide. Here's a working example, which works with AOT compilation in Angular 7:
https://github.com/johncrim/angular-dynamic-styleguide
该项目的README.md提供了一些有关我遇到的问题以及如何解决这些问题的其他信息。
The README.md for that project provides some additional info on the problems I came up against and how I figured out the fixes.
这篇关于在Angular 5和AOT-Build中使用@angular编译器时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!