我有一个包含节点的递归树结构,每个节点都有一个“htmlStringContent”属性。当我使用嵌套的“节点”组件显示树并尝试呈现我使用的 html 内容时:
<div [innerHtml]="node.htmlStringContent"></div>
HTML 显示正确,但对于以下元素:
<a (click)="function()">click me</a>
(单击)功能不起作用。我知道这有 previously been posted但是随着最近 Angular 带来的大量更新,我找不到任何解决方案。 This answer让我相信我应该使用 ngComponentOutlet 指令,但我不确定如何......
如何获得 Angular 来绑定(bind)此点击功能?
编辑:有人告诉我使用 ComponentFactoryResolver,但看不出如何使用它来正确显示 html。谁能提供进一步的帮助?
Edit2:我在 [innerHtml] 上显示之前通过清理管道解析“htmlStringContent”
transform(v: string) : SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(v);
}
Edit3:这个问题基本上是在询问是否有可能在 angular 2/ionic 2 中从对象的属性显示 HTML,同时保留其上的(点击)功能。我也愿意接受解决方法的答案。
最佳答案
CFR 演示:https://plnkr.co/edit/jKEaDz1JVFoAw0YfOXEU?p=preview
@Component({
selector: 'my-app',
template: `
<button (click)="addComponents()">Add HTML (dynamically using CRF)</button>
<h1>Angular2 AppComponent</h1>
<hr>
<div>
<h5>dynamic html goes here</h5>
<div class="container">
<template #subContainer1></template>
</div>
</div>
`,
})
export class App {
name:string;
@ViewChild('subContainer1', {read: ViewContainerRef}) subContainer1: ViewContainerRef;
constructor(
private compFactoryResolver: ComponentFactoryResolver
) {
this.name = 'Angular2'
}
addComponents() {
let compFactory: ComponentFactory;
compFactory = this.compFactoryResolver.resolveComponentFactory(Part1Component);
this.subContainer1.createComponent(compFactory);
}
}
关于angular - 使用(单击)函数动态显示包含 HTML 的元素 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242903/