在Angular 5和AOT-Build中使用@angular编译器时出错

问题描述 投票:5回答:1

我正在使用Angular Compiler在运行时编译组件。此代码工作正常,但如果我想使用AOT-Prerendering,则组件不起作用,因为Angular不会在AOT-Build中加载编译器。

我已经阅读了一些不再适用于Angular5 +的变通方法。你对这个问题有什么解决方案吗?

最好的祝福


    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);
      }
    }
runtime angular5 aot
1个回答
0
投票

你可以用一些技巧来完成这项工作。我去年遇到了同样的问题,并找到了解决办法。我在我的样式指南中使用动态生成的角度组件。这是一个工作示例,它与Angular 7中的AOT编译一起使用:

https://github.com/johncrim/angular-dynamic-styleguide

该项目的README.md提供了一些关于我遇到的问题的额外信息以及我如何找出修复方法。

© www.soinside.com 2019 - 2024. All rights reserved.