angular6解析模板字符串,$compile服务在angular6中的实现方法

angular6解析动态字符串模板

依赖:

  1. Compiler服务
  2. viewContanierRef服务

步骤:

  1. 创建指令,并通过指令接受字符串
  2. 接受字符串,并通过此字符串动态创建组件及模块
  3. compiler服务解析组件和模块
  4. 通过将解析出来的组件添加到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>`;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值