【问题标题】:Using an api call value as background image to a div in my Angular app在我的 Angular 应用程序中使用 api 调用值作为 div 的背景图像
【发布时间】:2019-04-05 13:53:11
【问题描述】:

我正在创建一个电影搜索应用程序,需要使用图像作为 div 的背景。我从 api 调用中获取背景图像的 url。

我试过了

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

还是没有运气。

有人知道我该如何解决这个问题吗?##标题##

【问题讨论】:

    标签: html css angular themoviedb-api


    【解决方案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 + '\')');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2013-11-14
      • 2015-06-20
      相关资源
      最近更新 更多