使用DomSanitizer

时间:2017-07-27 12:54:59

标签: angular ionic2 innerhtml

<!--HTML CODE-->
<p #mass_timings"></p>

//controller code

@ViewChild('mass_timings') mass_timings: ElementRef;
constructor(private domSanitizer:DomSanitizer)
getInnerHTMLValue(){
 this.mass_timings.nativeElement.innerHTML = 
   this.domSanitizer.bypassSecurityTrustHtml(this.parishDetail.mass_timings);

}

但是mass_timings正在显示的输出包括文本: -

  

安全值必须使用[property] = binding

开头

如何删除此字符串。

6 个答案:

答案 0 :(得分:21)

正如错误消息所示,需要使用属性绑定添加已清理的HTML:

<p [innerHTML]="massTimingsHtml"></p>
constructor(private domSanitizer:DomSanitizer) {
  this.massTimingsHtml = this.getInnerHTMLValue();
}
getInnerHTMLValue(){
  return this.domSanitizer.bypassSecurityTrustHtml(this.parishDetail.mass_timings);
}

StackBlitz example(基于Swapnil Patwa的Plunker - 见下面的评论)

答案 1 :(得分:4)

我在使用iframe时遇到此错误,因此我使用[src]进行了修复,如下所示:

//In ts file
getSafeUrl() {
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);     
}
//In html
<iframe [src]="getSafeUrl()" frameborder="0" *ngIf="url"></iframe>

这种方法非常耗费周期,因为它会多次调用函数,因此最好清理lifeCycleHooks中的URL,如ngOnInit()

答案 2 :(得分:2)

在angular 7中使用MATHJAX时遇到了相同的错误。我通过以下管道变换解决了。 100%完美地工作

//消毒HTML PIPE

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

@Pipe({
    name: 'sanitizeHtml'
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) {
    }

    transform(value: string): SafeHtml {
        return this._sanitizer.sanitize(SecurityContext.HTML, this._sanitizer.bypassSecurityTrustHtml(value))
    }
}

答案 3 :(得分:2)

我使用管道的解决方案。

HTML

<div [innerHtml]="htmlValue | byPassSecurity"></div>

管道

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

@Pipe({
    name: 'byPassSecurity'
})
export class ByPassSecurityPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) {}

    transform (value: string): SafeHtml {
        return this.sanitizer.bypassSecurityTrustHtml(value);
    }
}

答案 4 :(得分:1)

您不需要在任何地方都绑定到 [innerHtml]

它的工作原理是将 sanitize()bypassSecurityTrustHtml() 一起使用,如下所示:

this.mass_timings.nativeElement.innerHTML = (
    this.domSanitizer.sanitize(SecurityContext.HTML, this.domSanitizer.bypassSecurityTrustHtml(this.parishDetail.mass_timings))
);

答案 5 :(得分:0)

您需要像这样清除安全值:

this.domSanitizer.sanitize(SecurityContext.HTML,this.domSanitizer.bypassSecurityTrustHtml(this.parishDetail.mass_timings));