如何动态地添加带有angular 2组件的innerHTML [英] How to dynamically add innerHTML with angular 2 components

查看:114
本文介绍了如何动态地添加带有angular 2组件的innerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为组件库创建文档.我想要1个html字符串,可以同时生成页面上的组件和文档.

I'm creating docs for a component library. I want 1 string of html that generates both the component on the page and the docs for it.

我想要什么:

我所拥有的:

当我检查HTML时,我的按钮标签不存在.当我使用innerHTML时,它们被剥夺了.

When I inspect the HTML, my-button tags are not present. They are being stripped out when I use innerHTML.

我的组件代码:

private flatButtons = `<div class="button-wrapper">
      <my-button [type]="'default'" [raised]="false">Default</my-button>
    </div>
    <div class="button-wrapper">
      <my-button [type]="'primary'" [raised]="false">Primary</my-button>
    </div>
    <div class="button-wrapper">
      <my-button [type]="'success'" [raised]="false">Success</my-button>
    </div>
    <div class="button-wrapper">
      <my-button [type]="'info'" [raised]="false">Info</my-button>
    </div>
    <div class="button-wrapper">
      <my-button [type]="'warning'" [raised]="false">Warning</my-button>
    </div>
    <div class="button-wrapper">
      <my-button [type]="'danger'" [raised]="false">Danger</my-button>
    </div>`

constructor() {}

getCode() {
    return html_beautify(this.flatButtons, this.options)
}

我的HTML模板:

<div class="row">
<div class="col-sm-6 col-xs-12">
  <mi-card title="Flat Buttons" baCardClass="with-scroll button-panel">
    <div id="flatButtons" [innerHTML]="getCode()">
    </div>
  </mi-card>
</div>
<div class="col-sm-6 col-xs-12">
  <pre>{{getCode()}}</pre>
</div>

推荐答案

Angular不会处理动态添加的HTML,它只是逐字添加,只是为了防止安全问题进行了一些清理. 参见RC.1中的样式不能使用绑定语法添加,以防止如何清除HTML.

Angular doesn't process HTML added dynamically, it just adds it verbatim except some sanitization to prevent security issues. See In RC.1 some styles can't be added using binding syntax for how to prevent the sanitizer of stripping the HTML.

您可以使用ViewContainerRef.createComponent(),如

You can use ViewContainerRef.createComponent() like shown in Angular 2 dynamic tabs with user-click chosen components to add components dynamically.

还有一些可用的解决方案,例如如何动态创建组件,如等效于Angular 2中的$ compile

There are also solutions available how to create components dynamically like shown in Equivalent of $compile in Angular 2

这篇关于如何动态地添加带有angular 2组件的innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆