angular - 使用(单击)函数动态显示包含 HTML 的元素 Angular 2

标签 angular typescript2.0

我有一个包含节点的递归树结构,每个节点都有一个“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/

相关文章:

angular - 使用 TypeScript 在 Angular 管道中使用 MapToIterable

angular - 空注入(inject)器错误: No provider for ElementRef

angular - 在 Angular2 中使用子/辅助路由(命名路由器)时如何删除 URL 中的括号?

javascript - TypeError : request. headers.entries 不是函数

inheritance - 在 TypeScript 中是否有等同于 "sealed"或 "final"的东西?

c# - typescript 升级 1.8.10 到 2.9.2 和 4.6.4 构建错误

css - 双边框底垫输入 Angular

java - Spring启动Angular2,以JSON返回PDF

javascript - Firebase getDownloadURL() 不返回任何内容

javascript - 如何在 typescript 中使用带有变量的可选链接运算符