问题
I have a big trouble with Angular 2 ngStyle directive. I can't set background image from base64 encoded file. Now in template.html I have this:
<div class="projects_item_wrap" [ngStyle]="{'background-image':'url('+images[i].file+')'}">
Where 'images' is an array of base64 encoded .png files and their names.
Console.log of images[3].file give me this (trouble not inside an image, it works perfectly when I use it in img src='...'):
Any ideas? Thanks a lot for answers! :)
回答1:
Linebreaks within received base64 image was a reason of trouble. This is my solution:
//This goes to template <div>:
[style.background-image]="makeTrustedImage(images[i].file)"
//And this goes to component:
constructor(private domSanitizer: DomSanitizer) {}
makeTrustedImage(item) {
const imageString = JSON.stringify(item).replace(/\\n/g, '');
const style = 'url(' + imageString + ')';
return this.domSanitizer.bypassSecurityTrustStyle(style);
}
来源:https://stackoverflow.com/questions/46041210/angular-2-ngstyle-and-background-image