html - 在我的 Angular 应用程序中使用 api 调用值作为 div 的背景图像

标签 html css angular themoviedb-api

我正在创建一个电影搜索应用程序,需要使用图像作为 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>

这是我收到的警告

警告:清理不安全的样式值 background-image: url(https://image.tmdb.org/t/p/w500/fw02ONlDhrYjTSZV8XO6hhU3ds3.jpg)

并且图像不显示。

然后我在其中一个值上尝试这个,看看它是否会起作用

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

但我还是遇到了同样的问题??

然后我试了一下

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

仍然没有运气。

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

最佳答案

看起来您非常熟悉使用 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 + '\')');
}

关于html - 在我的 Angular 应用程序中使用 api 调用值作为 div 的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55536949/

相关文章:

带有缓动和 stellar.js 的 javascript 水平视差

html - 带有不透明动画的双背景 DIV 一两个单独的图像

CSS 按钮定位 - 包括 fiddle

html - 使div(height)占据父级剩余高度

angular - 为什么更改事件会在 controlValueAccessor 模糊时触发

javascript - 在 Angular 中单击时重置 rxjs 间隔

javascript - 无法使用 "ng new"命令通过 ng cli 创建新项目

javascript - 如何从密码字段中隐藏除一个字符以外的所有字符

html - div 在另一个绝对定位的 div 之下

jquery - CSS(也许 Jquery 也是)在页面的第一次加载(在 IE 中)不能正常工作