angular6解析动态字符串模板
依赖:
- Compiler服务
- viewContanierRef服务
步骤:
- 创建指令,并通过指令接受字符串
- 接受字符串,并通过此字符串动态创建组件及模块
- compiler服务解析组件和模块
- 通过将解析出来的组件添加到dom容器中
代码:
**指令代码:**
import {Compiler, Component, Directive, Input, NgModule, OnChanges, OnInit, TemplateRef, ViewContainerRef} from '@angular/core';
import {DynamicModuleModule} from './dynamic-module/dynamic-module.module';
@Directive({
selector: '[appTestDirective]'
})
export class TestDirectiveDirective implements OnChanges {
constructor(public viewContaier: ViewContainerRef, private myCompiler: Compiler) {
}
//接受字符串
@Input()
appTestDirective: string;
ngOnChanges(): void {
//在dom容器中添加组件并显示
this.createDynamicCmd().then((cmdFac)=>{
this.viewContaier.createComponent(cmdFac);
})
}
//动态创建组件
createDynamicCmd() {
if (!this.appTestDirective) return;
let father=this;
@Component({
template: father.appTestDirective,
})
class dynamicComponent {
}
@NgModule({
imports:[DynamicModuleModule],
declarations: [dynamicComponent]
})
class dynamicModule {
}
return this.myCompiler.compileModuleAndAllComponentsAsync(dynamicModule).then(moduleWithCmd=>{
return moduleWithCmd.componentFactories.find((cmdFac)=>{
return cmdFac.componentType===dynamicComponent
})
})
}
}
**html代码**
<div>
<ng-template [appTestDirective]="template"></ng-template>
</div>
**控制器代码**
template:string=`<div><app-test-component2></app-test-component2></div>`;