简体   繁体   English

如何替换 Angular 中属性样式背景图像中给出的损坏图像 URL?

[英]How to replace a broken image URL given in attribute style background-image in Angular?

<img  [src]="item.imgUrl" (error)="pictNotLoading($event)" alt="" />

pictNotLoading(event) { 
    event.target.src = '/assets/dynamic_images/medvibe_partner.png'; 
} 

the above criteria will replace broken images.上述标准将替换损坏的图像。 In my products listing page, I've decided to set background-image dynamically for each product item (as like hover effect).在我的产品列表页面中,我决定为每个产品项目动态设置background-image (就像 hover 效果一样)。

<span class="product_thumbnail_hover" style="background-image:url('{{item.imgUrl}}');"></span>

But somehow I'm getting a bunch of broken image URLs from api call.但不知何故,我从 api 调用中得到了一堆损坏的图像 URL。 So, my question is how to replace a broken image url given in style background-image所以,我的问题是如何替换背景图像中给出的损坏图像 url

span tag is inline-block element, so you need change display and set width & height for it. span标签是 inline-block 元素,因此您需要更改显示并为其设置宽度和高度。 for example if use p tag, you didn't need add display: block;例如,如果使用p标签,则不需要添加display: block; . .

Try like this:试试这样:

<span style="background:url('{{ item.imgUrl }}');display:block; height:100vh; width:100vw; background-repeat: no-repeat"></span>

snippet:片段:

 <span style="background:url('https://picsum.photos/200/300');display:block; height:100vh; width:100vw; background-repeat: no-repeat"></span>

<ng-template [ngIf]="item.imgUrl != null || item.imgUrl != undefined">
     <span class="product_thumbnail_hover" [ngStyle]="{'background-image': item.imgUrl ? 'url(' + item.imgUrl + ')' : 'url(' + '/assets/dynamic_images/prod_preview.png' + ')'}"></span>
</ng-template>

Above code resolved my issue temporarily.上面的代码暂时解决了我的问题。 I don't know is this a good or worst method.我不知道这是一个好方法还是最坏的方法。 think this might helps.认为这可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM