【问题标题】:Compile dynamically created HTML to existing component将动态创建的 HTML 编译到现有组件
【发布时间】:2017-12-25 13:39:53
【问题描述】:

我有一个组件,其中有一个将以下 HTML 插入 DOM 的 3rd 方库:

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

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

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

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

有什么想法吗?

【问题讨论】:

  • 你真的需要改变你的策略。 Angular 应用程序在生产中是(或至少应该)使用 AOT 编译器编译的,这正是为了使事情变得更快,并且不允许将 Angular 编译器与应用程序一起交付,使其也更小。因此,在运行时编译东西甚至不再可能了。您当然可以决定不这样做,但您将与框架及其最佳实践作斗争。

标签: angular


【解决方案1】:

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() {
  ...
}

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 2020-02-20
    • 2018-05-31
    • 2016-07-02
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多