Is there a way to render Angular template on runtime?

278 Views Asked by At

I'm using Angular 16.0.3 and I'm trying to make a component that receives a template string and render it at runtime. The template string can contain Angular components in it and will probably be fetched from a server.

I based myself on this StackOverflow question: Render an Angular string template at runtime.

I tried this:

dynamic-template.component.ts

import { Component, Input, ViewChild, ViewContainerRef, ɵcompileComponent } from '@angular/core';

@Component({
selector: 'app-dynamic-template',
template: '\<ng-container #container\>\</ng-container\>'
})
export class DynamicTemplateComponent {
@Input() content: string
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef

constructor() {}

generate(): void {
const component = getComponentFromTemplate(this.content)
this.container.clear();
const componentRef = this.container.createComponent(component);
console.log(componentRef)
}
}

@Component({
template: '',
}) class TemplateComponent {
@ViewChild('heading') heading: HTMLHeadingElement
}

function getComponentFromTemplate(template: string) {
ɵcompileComponent(TemplateComponent, {
template,
standalone: true,
});

return TemplateComponent;
}

But I'm getting this:

Console

JIT compilation failed for component class TemplateComponent {}
ERROR Error: The component 'TemplateComponent' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.

JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.
Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',
or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.
at getCompilerFacade (core.mjs:5088:15)
at TemplateComponent.get \[as ɵcmp\] (core.mjs:24683:34)
at getComponentDef (core.mjs:1839:16)
at ViewContainerRef.createComponent (core.mjs:23218:31)
at DynamicHtmlComponent.generate (dynamic-html.component.ts:16:41)
at GuestComponent.generate (guest.component.ts:16:27)
at GuestComponent_Template_button_click_3_listener (guest.component.html:3:20)
at executeListenerWithErrorHandling (core.mjs:15700:16)
at wrapListenerIn_markDirtyAndPreventDefault (core.mjs:15733:22)
at HTMLButtonElement.\<anonymous\> (platform-browser.mjs:666:17)

My Questions

  1. How can I fix this?
  2. Is there a way to make only one lazy loaded child module to use the JIT compiler and if yes, how can I do it?
1

There are 1 best solutions below

0
user23369653 On

In your angular.json file, under architect:build.options, add/set "aot":false

As per various documentation, it is not recommended to use in production.