【问题标题】:Angular component that takes HTML code as input将 HTML 代码作为输入的 Angular 组件
【发布时间】:2019-11-27 11:45:45
【问题描述】:

我正在创建一个显示突出显示的 HTML 代码及其执行结果的 Angular 组件。显示的 HTML 代码位于 pre html 元素中,至于结果的预览,它是硬编码的:

<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>

使用该组件的结果如下 following

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

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

输入显示为字符串但未执行的内容显示为 HTML 代码:image

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

感谢您的帮助。

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    解决方案是创建一个绕过安全信任 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 字符串的地方使用它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 2013-04-23
      • 2016-04-20
      • 2019-04-06
      • 2018-04-05
      相关资源
      最近更新 更多