0

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 Answer 1

1

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 + '\')');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.