I'm creating a movie searching app and need to use an image as the background of a div. I get the url for the background image from an api call.

I tried this

<div *ngFor="let movie of movies.results">
  <div
    class="thumbnail" style="background-image: 
    url(https://image.tmdb.org/t/p/w500{{movie.poster_path}})"
  >
    -- id: {{ movie.id }} -- name: {{ movie.title }}
  </div>
</div>

this is the warning I get

WARNING: sanitizing unsafe style value background-image: url(https://image.tmdb.org/t/p/w500/fw02ONlDhrYjTSZV8XO6hhU3ds3.jpg)

and the image doesn't display.

I then try this on one of the values to see if it'll work

this.sanitizer.bypassSecurityTrustUrl(` https://image.tmdb.org/t/p/w500"${this.movies.results[0].poster_path} `);

but I still run into the same problem??

I then tried this

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

Still no luck.

Anybody know how I can solve this problem?## Heading ##

1 Answers

1
peinearydevelopment On Best Solutions

It looks like you were really close with using the DomSanitizer and bypassSecurityTrustUrl. I believe using the same approach but using bypassSecurityTrustStyle should solve the problem for you.

<div *ngFor="let movie of movies.results">
  <div
    class="thumbnail" [style.background-image]="getSafeStyle(movie.poster_path)"
  >
    -- id: {{ movie.id }} -- name: {{ movie.title }}
  </div>
</div>

getSafeStyle(url: string) {
  return this.sanitizer.bypassSecurityTrustStyle('url(\'' + url + '\')');
}