将HTML代码作为输入的Angular组件 [英] Angular component that takes HTML code as input

查看:66
本文介绍了将HTML代码作为输入的Angular组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个角度组件,该组件显示突出显示的HTML代码及其执行结果.显示的HTML代码位于pre html元素内,作为结果预览,它是硬编码的:

I am creating an angular component that displays a highlighted HTML code and the result of it's execution. The displayed HTML code lives inside a pre html element, as for the preview of the result, it's hard-coded :

<pre class="prettyprint lang-html">

&lt;button type="button" class="btn btn-danger">Danger&lt;/button> <br> &lt;p> Hello World! &lt;/p>

</pre>

<button type="button" class="btn btn-danger">Danger</button>
<p> Hello Wolrd </p>

使用此组件的结果是关注

现在我要做的就是将此HTML代码作为输入传递给该组件.我尝试使用以下字符串将代码作为字符串传递:

Now what I want to do is to pass this HTML code as an input to this component. I tried to pass the code as a string using the following string :

&lt;button type=\"button\" class=\"btn btn-danger\">Danger&lt;/button> <br> &lt;p> Hello World! &lt;/p>

显示为字符串但未执行的输入显示为HTML代码:图像

The input what displayed as a string and was not executed displayed as an HTML code : image

我如何使用此输入字符串来1.将其显示为html代码,并2.执行此代码以预览结果?否则,我应该为输入使用什么类型?

How can i use this input string to 1. display it as html code and 2. execute this code to preview the result ? Otherwise, what's the type that i should use for the input ?

感谢您的帮助.

推荐答案

解决方案是创建一个绕过安全信任html的自定义管道:

Solution for this is to create a custom pipe that bypass security trust html:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({name: 'sanitizeHtml'})
export class SanitizeHtmlPipe implements PipeTransform {
  constructor(private _sanitizer:DomSanitizer) {
  }
  transform(v:string):SafeHtml {
    return this._sanitizer.bypassSecurityTrustHtml(v);
  }
}

在模块中声明它,并在要显示HTML字符串的位置使用它:

Declare it in your module and use it where you want to display the HTML string :

<div [innerHTML]=" yourHTMLstring | sanitizeHtml "> </div>

这篇关于将HTML代码作为输入的Angular组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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