I am creating a dynamic component in Angular 9. I have a <ul> tag in the html template, the sub-elements of which are dynamically loaded from the server (The server will return values like <li>One</li><li>Two</li><li (click)="onLinkClicked(3)">Three</li> using handlebar templates).

    private createComponentFromRaw(template: string, containerRef: ElementRef) {
        class DynamicComponent {
            onLinkClicked(resource: any) {
                console.log(resource);
            }
        }

        ɵcompileComponent(DynamicComponent, { template, changeDetection: ChangeDetectionStrategy.OnPush });
        ɵrenderComponent(DynamicComponent, {
            host: containerRef.nativeElement,
            injector: this.injector,
            hostFeatures: [ɵLifecycleHooksFeature],
        });
    }

On calling this.createComponentFromRaw('<li>One</li>', this.ref.element); the component is rendered as expected when run as ng serve but throws the following error at runtime in production mode (ng build --prod):

ERROR Error: Angular JIT compilation failed: '@angular/compiler' not loaded!
  - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.
  - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?
  - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.
1

There are 1 best solutions below

0
On

Looks like the only option currently available is to set buildOptimizer: false in the angular.json

This happens because the buildOptimizer incorrectly considers @angular/compiler as having no side-effects and removes it as part of the tree shaking