Angular 2:在innerHTML

时间:2017-03-16 14:21:31

标签: angular typescript webpack typescript2.0

我有2个@components说和。现在,我必须动态加载innerHTML,例如:如下

组件1.HTML

<div [innerHTML]="domEl | safeHtml"></div>

在Angular2组件-1类

import {
  Component,
  OnInit,
  ViewEncapsulation
} from '@angular/core';


@Component({  
  selector: 'component-1',

  templateUrl: './component-1.html',

  encapsulation: ViewEncapsulation.None
})
export class Component1 implements OnInit {    

  public ngOnInit() {
    this.domEl = '<component-2 data="1234"></component-2>'
  }
}

component-2已经通过声明[]注入app.module.ts文件中。 safeHtml也是用于安全HTML转换的管道。

即便如此,问题是组件-2未加载。任何人都可以建议我如何解决这个问题?

注意:

  • 如果我直接在component-1.html中包含component-2就可以了。但我们有一个案例,我们不能动态注入组件-2。
  • Stack是基于Angular2,TypeScript和Webpack构建的。

1 个答案:

答案 0 :(得分:0)

为了安全起见,Angular不会处理传递给[innerHTML]="..."的HTML,除了清理。不会创建绑定,组件,指令......,因为如上所述,Angular会忽略内容。您可以做的是在运行时创建一个组件,如Equivalent of $compile in Angular 2中所述。 AFAIR有人建立了一个模块,使这更容易,但我不记得细节。