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

1

5

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);
      }
    }
Imago answered 19/1, 2018 at 10:56 Comment(0)
A
0

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.

Azeotrope answered 22/3, 2019 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.