【问题标题】:Angular 2: Loading dynamic component in innerHTMLAngular 2:在innerHTML中加载动态组件
【发布时间】:2017-03-16 14:21:30
【问题描述】:

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

component-1.html

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

在 Angular2 component-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,它将起作用。但是我们遇到了一个不能动态注入 component-2 的情况。
  • Stack 基于 Angular2、TypeScript 和 Webpack 构建。

【问题讨论】:

  • 不要加载 innerHtml,而是使用带有 ngIf 或 ngSwitch 的模板。
  • 不能那样做,在我的情况下这行不通。
  • 您不能将组件注入为 html。组件从 Shadow Dom 渲染到 Real Dom。当你使用 innerHTML 注入一些东西时,它应该是原始的 Html,而不是需要渲染管道的东西。正如我之前所说,你必须使用 ngIf 或 ngSwitch

标签: angular typescript webpack typescript2.0


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-21
    • 2017-10-21
    • 2017-12-15
    • 2017-02-02
    • 1970-01-01
    • 2021-01-10
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多