3

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='...'):

blob image

Any ideas? Thanks a lot for answers! :)

Wondergrauf
  • 168
  • 1
  • 9

1 Answers1

2

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);
  }
Wondergrauf
  • 168
  • 1
  • 9