I'm working on an Angular 13 project, and I need to render dynamic components. The component template and the biz logic come from the server-side as a string. I read that you can't create templates dynamically in Angular 13, as any component must be compiled by Angular at build time, and Angular apps do not ship with the JIT compiler.
This is only for one part of the application where I allow customers to build their custom dashboards.
It was possible to do that in Angular 12, but in Angular 13 the compiler service is no longer exposed.
Code working in Angular 12:
Template:
<div>
<ng-container *ngComponentOutlet="component"></ng-container>
</div>
Component:
import { Compiler, Component, NgModule, OnInit } from '@angular/core'
@Component({
selector: 'my-lab',
templateUrl: './lab.component.html',
styleUrls: ['./lab.component.scss'],
})
export class LabComponent implements OnInit {
component: any
constructor(private compiler: Compiler) {}
async ngOnInit() {
const componentClass = class {
public testing = {
name: 'yago',
}
}
const imports = (this.component = await this.compile({
template: `<div>Testing here {{ testing | json}}</div>`,
componentClass,
imports: [CommonsModule],
}))
}
async compile(input: any) {
const { template, componentClass, imports } = input
const templateCompoment = Component({ template })(componentClass)
const module = NgModule({
declarations: [templateCompoment],
exports: [templateCompoment],
imports: [...imports],
})(class {})
const compiledModule = await this.compiler.compileModuleAndAllComponentsAsync(module)
return templateCompoment
}
}
I wonder if you need to use a different set of APIs in Angular 13 or higher to be able to do this. Has anyone done this?
Maybe this could help you if I understand correctly what you want to do https://material.angular.io/cdk/portal/overview