将动态创建的HTML编译为现有组件

时间:2017-12-24 17:29:11

标签: angular

我有一个组件,其中有第三方库将以下HTML插入DOM:

<input (click)="doSomething()"/>{{someText}}

doSomething是我的组件中的一个函数,{{someText}}是一个属性。

我正在尝试找出将此字符串编译为现有组件的方法,而不是使用ComponentFactoryResolver创建新字符串。

我尝试附加动态HTML,然后使用ChangeDetectorRef.detectChanges()NgZone.run(callback)ApplicationRef.tick()。这些都没有编译HTML。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如何使用ViewContainerRef.createEmbeddedView

模板:

<!-- location in your component template to add the dynamic template -->
<ng-container #ref></ng-container>

...

<!-- dynamic template definition -->
<ng-template #tpl>
  <input (click)="doSomething()"/>{{someText}}
</ng-template>

组件类:

someText: string;

@ViewChild('ref')
vcr: ViewContainerRef; 

@ViewChild('tpl')
tpl: TemplateRef;

ngOnInit() {

  myLib.onSomeEvent(() => {
    this.vcr.createEmbeddedView(this.tpl); 
  })
}

doSomething() {
  ...
}