Updated on Kisan Patel
Learn how to use a dynamic template to compile dynamic Component with Angular?
First generate the compiler service to compile dynamic html string using following command:
ng g s RuntimeCompiler
runtime-compiler.service.ts
import { Compiler, Component, Injectable, ModuleWithComponentFactories, NgModule, NgModuleFactory, Type } from '@angular/core'; import { FormsModule } from '@angular/forms'; export class DynamicTemplate { constructor( public readonly template: string, // tslint:disable-next-line:no-any public readonly component: Type<any>, // tslint:disable-next-line:no-any public readonly moduleFactory?: NgModuleFactory<any> ) { } } @Injectable({ providedIn: 'root' }) export class RuntimeCompilerService { private compiledModule?: ModuleWithComponentFactories<any>; public async createAndCompileTemplate(context, template: string): Promise<DynamicTemplate> { const dynamicComponent = Component({ template })( class { context = context; } ); const dynamicModule = NgModule({ declarations : [ dynamicComponent ], exports : [ dynamicComponent ], entryComponents: [ dynamicComponent ], imports : [ FormsModule, //add more module ] })(class DynamicModule { }); this.compiledModule = await this.compiler.compileModuleAndAllComponentsAsync(dynamicModule); return new DynamicTemplate(template, dynamicComponent, this.compiledModule.ngModuleFactory); } constructor(private compiler: Compiler) { } }
Usage:
app.component.ts
import { Component } from '@angular/core'; import { DynamicTemplate, RuntimeCompilerService } from './runtime-compiler.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { name = 'JitCompilerFactory'; text = '<input [(ngModel)]="context.name"> // type anything here' dynamicTemplate: DynamicTemplate; generate() { this.runtimeCompilerService.createAndCompileTemplate(this, this.text).then(data => { this.dynamicTemplate = data; }); } constructor(private runtimeCompilerService: RuntimeCompilerService) { } }
app.component.html
<div class="dynamic-area" *ngIf="dynamicTemplate"> <ng-container *ngComponentOutlet="dynamicTemplate.component;ngModuleFactory:dynamicTemplate.moduleFactory"></ng-container> </div>