[英]dynamic image path not showing in [style.background-image] property in Angular 7
I am trying to use dynamic image path as background image in one of my Angular6 project. 我试图在我的一个Angular6项目中使用动态图像路径作为背景图像。 I have tried using [style.background-image] & [style.background] even encodeURI to fix spaces in path also tried using *ngIF so that it renders after getting loaded. 我尝试使用[style.background-image]和[style.background]甚至encodeURI来修复路径中的空格也尝试使用* ngIF,以便在加载后呈现。
Case 1: 情况1:
imgPath is the absolute path, to which I am appending the path from JSON data. imgPath是绝对路径,我将JSON数据附加到路径。
HTML code HTML代码
<a routerLink="/article/{{news.id}}">
<img [style.background-image]="'url(' + imgPath + news.encodedImage.encocoded_primary_image + ')'">
</a>
Component 零件
Checking images for spaces and other bracket using encodeURI() function 使用encodeURI()函数检查空间和其他支架的图像
'encocoded_primary_image': encodeURI(res['primary_image']['file_path'])
Output 产量
Image comparison of article 文章的图像比较
Other cases 其他情况
I have tried with [style.background]
, [ngStyle]
, changing image tag to div tag. 我尝试过[style.background]
, [ngStyle]
,将图像标记更改为div标记。
But i am not able to understand why few of the images are rendering and few are not rendering, though path is getting generated correctly, which I have confirmed by opening them in new tab. 但我无法理解为什么很少有图像正在渲染而很少有渲染,尽管路径生成正确,我已通过在新标签中打开它们来确认。
Any help will be highly appreciated 任何帮助将受到高度赞赏
background-image: url
accepts the string. 在background-image: url
接受字符串。 You have to add your image path to a string. 您必须将图像路径添加到字符串。 "'url(\\'' + imgPath + news.encodedImage.encocoded_primary_image + '\\')'"
<a routerLink="/article/{{news.id}}"> <img [style.background-image]="'url(\\'' + imgPath + news.encodedImage.encocoded_primary_image + '\\')'"> </a>
https://developer.mozilla.org/en-US/docs/Web/CSS/background-image https://developer.mozilla.org/en-US/docs/Web/CSS/background-image
https://www.w3schools.com/csSref/pr_background-image.asp https://www.w3schools.com/csSref/pr_background-image.asp
Try using escape() method but this method has been deprecated. 尝试使用escape()方法,但不推荐使用此方法。 Careful using this. 小心使用这个。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.