Angular 2 disable sanitize

后端 未结 3 585
野的像风
野的像风 2020-12-04 02:21

I am trying to render base64 string into .

But always when I try to render it, ng2 sanitizing my base64 str

相关标签:
3条回答
  • 2020-12-04 02:26

    After unsuccessfully trying to get the bypassSecurityTrust... functions to work, I resorted to the following:

    @ViewChild('div_element_id') private div_element_id: ElementRef;
    ...
    
    this.div_element_id.nativeElement.innerHTML = bypass_security_for_this_html;
    
    0 讨论(0)
  • 2020-12-04 02:33

    After few hours of researches I have finally found that in latest version of ng2 there is no DomSanitizer that can be injected using DI, however there is Sanitizer. So here is the usage:

    constructor( private _sanitizer: Sanitizer){
    }
    
    get getImg() {
        return this._sanitizer.sanitize(SecurityContext.URL, `data:image/png;base64,${this.img}`);
    }
    
    <input src="{{getImg}}"/>
    

    As you can see first argument of sanitize method is SecurityContext instance, which basically is enum. So right now Sanitizer is a factory which choose the implementation to use based on SecurityContext

    In my case I had a problem that my base64 was sanitized before that get, that why I was not able to get it working.

    0 讨论(0)
  • 2020-12-04 02:50

    You need to explicitly tell Angular2 that the string is trusted

    https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

    constructor(private sanitizer:DomSanitizer) {}
    
    get imgBase64() {
      this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,$SomeBase64StringFetchedSomehow');
    }
    
    <img alt="RegularImage" [src]="imgBase64">
    

    See also In RC.1 some styles can't be added using binding syntax

    0 讨论(0)
提交回复
热议问题