简体   繁体   English

如何让Angular2绑定innerHTML中的组件

[英]How to get Angular2 to bind component in innerHTML

I want to create a component myApp that will embed HTML from a property on the controller in its template.我想创建一个组件myApp ,它将从控制器上的属性中嵌入 HTML 到其模板中。 However, some of that HTML may include other component selectors.但是,其中一些 HTML 可能包含其他组件选择器。

import {InfoComponent} from ...
@Component({
    selector: 'myApp',
    template: `<div [innerHTML]='hData'></div>
               <myInfo></myInfo>`,
    directives: [InfoComponent]
})
export class AppComponent {
   hData = "<myInfo></myInfo>";
}

@Component({
   selector: 'myInfo',
   template: "<b>This is a test</b>"
})
export class InfoComponent {
}

In this example, I would expect to see This is a test displayed twice.在这个例子中,我希望看到This is a test显示两次This is a test However, it doesn't appear that the Angular2 engine picks up on the fact that the selector of the Component has been injected so the template never gets generated for the <myInfo></myInfo> selector that is add via the binding.但是,Angular2 引擎似乎并没有发现 Component 的选择器已被注入的事实,因此永远不会为通过绑定添加的<myInfo></myInfo>选择器生成模板。

You can see a demo here .您可以在此处查看演示

Is there a way to get Angular2 to parse the selector in the same way it does with the selector that is added explicitly in the template?有没有办法让 Angular2 以与在模板中显式添加的选择器相同的方式来解析选择器?

There is no way to make [innerHtml]="..." instantiate Angular components or directives or establish any bindings.没有办法让[innerHtml]="..."实例化 Angular 组件或指令或建立任何绑定。

The closest for this requirement is DynamicComponentLoader . 最接近此要求的是 DynamicComponentLoader (DynamicComponentLoader was removed a while ago) ViewContainerRef.createComponent() (DynamicComponentLoader 不久前被移除) ViewContainerRef.createComponent()

See Angular 2 dynamic tabs with user-click chosen components for an example有关示例,请参阅Angular 2 dynamic tabs with user-click selected components

Since RC.5 Angular2 sanitizes styles and HTML added through binding.由于 RC.5 Angular2 清理了通过绑定添加的样式和 HTML。 See In RC.1 some styles can't be added using binding syntax for more details.有关更多详细信息,请参阅在 RC.1 中,无法使用绑定语法添加某些样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM