I'm creating Angular code at runtime, in particular, I use a SVG library in order to create a vector graphic that contains Angular code directives like (click)='myMethod()'
, which, in turn, call methods I've statically defined in the SVG-enclosing component. Being generated at runtime I need to compile the created template and add it to a component. I implemented such code back then with Angular 3 with the help of this post which was quite cumbersome. I tried to the copy the old code in an Angular 8 app:
private addComponent(template: string) {
@Component({template: template + ' <div #target></div>'})
class TemplateComponent {
@ViewChild('target', {static: false, read: ViewContainerRef}) public target;
constructor() {
}
public myMethod() {
// do something
}
}
@NgModule({declarations: [TemplateComponent]})
class TemplateModule {
@ViewChild('target', {static: false, read: ViewContainerRef}) public target;
}
// ERROR in next line:
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = mod.componentFactories.find((comp) =>
comp.componentType === TemplateComponent
);
this.container.createComponent(factory);
}
which now fails with
ERROR Error: Runtime compiler is not loaded at Compiler._throwError (core.js:38932)
On the one hand, I have no clue why that error occurs. Everything I found on the internet was about critical function syntax in lazy module loading. On the other hand, I wonder, if five Angular major versions later, there is an other way to do it. I read about Portals but it seems to be about loading static templates dynamically, but not uncompiled templates generated on the fly. Looking forward to someone pointing me in the right direction.
Post Scriptum: Adding a Bounty for the one that can provide a basic running code snippet targetting Angular v9 in AoT mode. It has to contain a runtime-compiled template (e.g. from a string variable) containing a method call in the associated component.
{path: 'user', loadChildren: () => import('./pages/user/user.module').then(m => m.UserModule), data: {breadcrumb: 'User'}}
– Betterment