angular2项目中html代码被安全过滤器筛掉的问题

2016-12-23  本文已影响1340人  琢磨先生lf

16.12.23 安全过滤器
需要渲染的代码如下:

<p><span class="spark-formula-frame" data-mml="%3Cmath%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1998%2FMath%2FMathML%22%3E%3Cmsqrt%3E%3Cmn%3E3%3C%2Fmn%3E%3C%2Fmsqrt%3E%3C%2Fmath%3E" data-latex="\sqrt{3}" scrolling="no" style="width: 26px; height: 21px;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-1" style="width: 1.372em; display: inline-block;"><span style="display: inline-block; position: relative; width: 1.313em; height: 0px; font-size: 105%;"><span style="position: absolute; clip: rect(1.074em 1001.31em 2.443em -999.997em); top: -2.08em; left: 0em;"><span class="mrow" id="MathJax-Span-2"><span class="msqrt" id="MathJax-Span-3"><span style="display: inline-block; position: relative; width: 1.313em; height: 0px;"><span style="position: absolute; clip: rect(3.158em 1000.48em 4.17em -999.997em); top: -3.985em; left: 0.836em;"><span class="mrow" id="MathJax-Span-4"><span class="mn" id="MathJax-Span-5" style="font-family: MathJax_Main;">3</span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.515em 1000.48em 3.932em -999.997em); top: -4.521em; left: 0.836em;"><span style="font-family: MathJax_Main;">–</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.039em 1000.84em 4.348em -999.997em); top: -3.985em; left: 0em;"><span style="font-family: MathJax_Main;">√</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.086em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.247em; border-left: 0px solid; width: 0px; height: 1.191em;"></span></span></nobr></span></p >

对比使用[innerHtml]指令与原生innerHtml:


解决方法:使用ng2服务DomSanitizer中的bypassSecurityTrustHtml
方法
具体操作:使用pipe过滤器进行封装。
import { DomSanitizer } from '@angular/platform-browser';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'bypassSecurityTrustHtml'
})

export class BypassSecurityTrustHtmlPipe implements PipeTransform {
    constructor(private domSanitizer: DomSanitizer){}
    transform(html: string, args: any[]): any {
        return this.domSanitizer.bypassSecurityTrustHtml(html);
    }
}

好处是不影响源数据

上一篇下一篇

猜你喜欢

热点阅读