0

Trying to set a background image using SafeUrl like this.

<h1>Image Test</h1>
<img [src]="imageURL" width="500px" height="500px">

<br>

<code>{{imageURL}}</code>

<div id="i" 
     class=".background-image"
     [ngStyle]="{'background-image': imageURL}">
></div>

The img tag renders, but the div does not.

Any ideas?

This is the Stackblitz demo:

https://stackblitz.com/edit/angular-blob-to-safe-url?file=src%2Fapp%2Fapp.component.html

The image is loaded like this:

this.loadImage().subscribe(i=>
{
     this.image = i
      this.imageURL = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(this.image))
})

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

1

Background-image property syntax for URLs is url("[URL]")

html

   <div id="i" 
         class=".background-image"
         [ngStyle]="{'background-image': getBackgroundImageUrl(imageURL)}">
    ></div>

ts

getBackgroundImageUrl(url) {
     return `url("${url.changingThisBreaksApplicationSecurity}")`;
}
Dusan Radovanovic
  • 1,599
  • 12
  • 21