Angular里使用createEmbeddedView动态加入新的模板元素

html源代码:

1
2
3
4
5
6
7
<div>
    <ng-template #tpl>
      <span>鬼子到我想干什么</span>
    </ng-template>
    <div #container></div>
    <button (click)="showTpl()">显示template</button>
  </div>

这部分源代码的运行时对应的原生html代码:

通过比较,html源代码里的ng-template代码没有出现在运行时的原生html代码:

1
2
3
    <ng-template #tpl>
      <span>鬼子到我想干什么</span>
    </ng-template>

showTpl的实现代码:

1
2
3
  showTpl() {
    this.container.createEmbeddedView(this.tt);
  }

点了按钮之后的html源代码:

效果就是以前被包裹在ng-template里用#命名的span元素,已经出现在了html源代码里: