问题
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