【问题标题】:Angular (2/5) rendering issue on html text with inline styles [duplicate]具有内联样式的html文本的角度(2/5)渲染问题[重复]
【发布时间】:2025-12-07 20:55:01
【问题描述】:

我在显示 HTML 数据时遇到问题,包括通过编辑器动态生成的内联样式(例如 TinyMCE)。 事实上,我已经使用innerHTML 绑定来显示html 数据。但是,它会忽略任何内联 style

例如:

我在component.ts 上有以下示例数据:

 let sampleData = '<h1><span style="background-color: #ffff99;">Welcome to the sample demo!</span></h1> <p><span style="color: #ff0000;">Please try out the features provided in this basic example.</span>'

我正在尝试在component.html上显示:

<div innerHTML="{{ sampleData }}"></div>

实际输出为:

欢迎使用示例 演示!

请试用 此基本示例中提供的功能。

预期输出:

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    很抱歉创建了重复的问题。

    但是,我在创建自定义管道后解决了这个问题

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser'
    
    /*
     * Pipe to avoid stripping the inline style on html text.
     *
     * Usage:
     *   safeHtml
     * Example:
     *  1. In Javascript:
     *      let input = new SafeHtml().transform(input);
     *
     *  2. In HTML:
     *      {{ safeHtml }}
    */
    
    @Pipe({ name: 'safeHtml'})
    
    export class SafeHtmlPipe implements PipeTransform  {
        constructor(private sanitized: DomSanitizer) {}
        transform(input) {
            return this.sanitized.bypassSecurityTrustHtml(input);
        }
    }
    

    应用管道:

    <div [innerHtml]="myHtmlContent | safeHtml"></div>
    

    参考来源:Angular2 innerHtml binding remove style attribute

    【讨论】: