3

I have a div in which I show a Base64 image using CSS:

.my-image {
    background: url('data:image/jpg;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
}

Now this image could be different because I retrieve it from back-end so I have to change it dinamically.

So I have removed CSS and I have tried some solution in the component such as the following:

<div [style.background]="'url(' + myImage + ')'"></div>

<div [ngStyle]="{'background-image':'url('+ myImage +')'}"></div>

and some others... but none worked.

I have also sanitized the image in the component, using some methods of DomSanitizer like this:

this.sanitizer.bypassSecurityTrustResourceUrl(this.myImage)

But even this doesn't do the trick :(

Do you know a working way to have div with dynamic background image?

Here is my CSS now:

div {
  width: 3em;
  height: 3em;
}
smartmouse
  • 13,912
  • 34
  • 100
  • 166

3 Answers3

7

I don't know why, but ngStyle removes first ";" it encounters in URL

My brilliant solution to this is pretty simple:

Turn this

[ngStyle]="{'background-image':'url('+ myImage +')'}"

Turn into this

[ngStyle]="{'background-image':'url(;'+ myImage +')'}"

Just aaded ; as first char in the url

Mcgri
  • 187
  • 1
  • 11
  • 1
    You are brilliant, after two hours of digging why. This is the best solution ever!!! Thanks! – André Machado Oct 28 '21 at 13:12
  • Ye, I gave up after 10 minutes :P Sometimes it's more productive to have an ugly hack...you just achieve more within the same amount of time. – Mcgri Nov 02 '21 at 10:58
4

Try like this:

.ts

myImage  = 'data:image/jpg;base64, iVBORw0KGgoA.....';

.html

<div [style.background-image]="'url(' + myImage  + ')'"> </div>

.css

div {
  height:500px;
  width: 500px;
}

Working Demo

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
3

I had the same problem as you and I solved it by using double semicolon ;; after the image extension, like this:

data:image/jpg;;base64

For some reason, in Angular 9 or earlier the string inside ngStyle directive was being rendered without any semicolon, like data:image/jpgbase64. The problem was solved, but I'd still like to know why it started to happen.

Miguel Trabajo
  • 437
  • 3
  • 11