Angular 2 disable disinfection

I am trying to convert a base64 string to <img src='data:image/png;base64,${Here}' .

But always, when I try to display it, ng2 sanitizes my base64 string before rendering, it adds something to my value before showing it in the DOM. I found a workaround (using DomSanitizer), but it does not work in recent versions.

Here is my markup:

 <img alt="RegularImage" src="data:image/png;base64,{{imgBase64}}"> 

And here is my component:

 imgBase64="SomeBase64StringFetchedSomehow"; 

But angular2 appears in the next console message - WARNING: sanitizing unsafe URL value

How to prevent NG2 from disinfecting my base64 string?

Update

 get getImg() { return this._sanitizer.sanitize(SecurityContext.URL,`data:image/png;base64,${this.img}`); } 

Does not resolve this issue. DomSanitizer class no longer exists in RC6

+5
source share
3 answers

After several hours of research, I finally found that the latest version of ng2 does not have DomSanitizer , which can be entered using DI, however there is Sanitizer . So here is the use:

 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, the first argument to the sanitize method is the SecurityContext instance, which is basically an enumeration. So right now, Sanitizer is a factory that selects the implementation used based on SecurityContext

In my case, I had a problem that my base64 was sanitized before that, so I could not get it to work.

+3
source

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 Cannot Be Added Using Binding Syntax

+5
source

After an unsuccessful attempt 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
source

All Articles