Error while using @angular compiler in Angular 5 and AOT-Build

放肆的年华 提交于 2019-12-10 14:44:19

问题


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.

I've read about some Workarounds that wont Work in Angular5+ anymore. Do you have any solutions for this problem?

Best Regards


    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);
      }
    }

回答1:


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

The README.md for that project provides some additional info on the problems I came up against and how I figured out the fixes.



来源:https://stackoverflow.com/questions/48339505/error-while-using-angular-compiler-in-angular-5-and-aot-build

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!