在我的Angular应用中将api调用值用作div的背景图像

时间:2019-04-05 13:53:11

标签: html css angular themoviedb-api

我正在创建一个电影搜索应用程序,需要将图像用作div的背景。我通过api调用获取了背景图片的网址。

我尝试过

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

这是我得到的警告

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

并且图像不显示。

然后我尝试对其中一个值进行尝试,看看它是否可以工作

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

但我仍然遇到相同的问题?

然后我尝试了

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

仍然没有运气。

有人知道我可以解决这个问题吗?##标题##

1 个答案:

答案 0 :(得分:1)

您似乎已经很熟悉使用DomSanitizer和bypassSecurityTrustUrl。我相信使用相同的方法但使用bypassSecurityTrustStyle应该可以为您解决问题。

<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 + '\')');
}