我正在创建一个电影搜索应用程序,需要使用图像作为 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+')'}"
仍然没有运气。
有人知道我如何解决这个问题吗?##标题##
看起来您对使用 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 + '\')');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句