Javascript Angular2:如果 img src 无效,则显示占位符图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36026428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2: Show placeholder image if img src is not valid
提问by user2263572
Goal: Load an image with a dynamic source. If no image is found, then load a placeholder image instead.
目标:加载带有动态源的图像。如果未找到图像,则加载占位符图像。
This should demonstrate what I'm trying to do, but I don't know how to conditionally set validImage
based on whether the first img
src
is valid.
这应该证明我正在尝试做什么,但我不知道如何validImage
根据第一个img
src
是否有效来有条件地设置。
<img *ngif="validImage" class="thumbnail-image" src="./app/assets/images/{{image.ID}}.jpg" alt="...">
<img *ngif="!validImage" class="thumbnail-image" src="./app/assets/images/placeholder.jpg" alt="...">
validImage
should be true
if src="./app/assets/images/{{image.ID}}.jpg"
returns an image. Otherwise it would return false
and only the second img
tag should show.
validImage
应该是true
如果src="./app/assets/images/{{image.ID}}.jpg"
返回图像。否则它会返回false
并且只显示第二个img
标签。
There are obvious work arounds like storing a list of all valid image sources, but I'm thinking there is a better way to accomplish this.
有明显的变通方法,例如存储所有有效图像源的列表,但我认为有更好的方法来实现这一点。
Any suggestions on the best way to implement this in Angular2 would be greatly appreciated.
任何关于在 Angular2 中实现这一点的最佳方式的建议将不胜感激。
回答by JanR
The best way to handle broken image links is the use the onError
event for the <img>
tag:
处理损坏的图像链接的最佳方法是使用标记的onError
事件<img>
:
<img class="thumbnail-image" src="./app/assets/images/{{image.ID}}.jpg"
onerror="this.src='./app/assets/images/placeholder.jpg';" alt="..." />
回答by Tiago Bértolo
<img [src]="pic" (error)="setDefaultPic()">
And somewhere in your component class:
在您的组件类中的某处:
setDefaultPic() {
this.pic = "assets/images/my-image.png";
}
回答by Chris Wheaton
I ran into a similar need. I wanted to default to a 1X1 transparent pixel if an img url was null or returned an error (404 etc).
我遇到了类似的需求。如果 img url 为空或返回错误(404 等),我想默认为 1X1 透明像素。
import { Directive, Input } from '@angular/core';
@Directive({
selector: 'img[src]',
host: {
'[src]': 'checkPath(src)',
'(error)': 'onError()'
}
})
export class DefaultImage {
@Input() src: string;
public defaultImg: string = '{YOUR_DEFAULT_IMG}';
public onError() {
this.src = this.defaultImg;
}
public checkPath(src) {
return src ? src : this.defaultImg;
}
}
Markup
标记
<img [src]="{DESIRED_IMAGE_SOURCE}" />
回答by Lucas Basquerotto
I've created a custom component that uses a placeholder image if the image is still not loaded or if an error occurs when loading it:
如果图像仍未加载或加载时发生错误,我创建了一个使用占位符图像的自定义组件:
img.component.ts:
img.component.ts:
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'my-img',
templateUrl: 'img.component.html',
})
export class ImgComponent implements OnChanges {
@Input()
public src: string;
@Input()
public default: string;
@Input()
public alt: string;
public cached = false;
public loaded = false;
public error = false;
private lastSrc: string;
constructor() { }
public ngOnChanges() {
if (this.src !== this.lastSrc) {
this.lastSrc = this.src;
this.loaded = false;
this.error = false;
this.cached = this.isCached(this.src);
}
if (!this.src) {
this.error = true;
}
}
public onLoad() {
this.loaded = true;
}
public onError() {
this.error = true;
}
private isCached(url: string): boolean {
if (!url) {
return false;
}
let image = new Image();
image.src = url;
let complete = image.complete;
// console.log('isCached', complete, url);
return complete;
}
}
img.component.html:
img.component.html:
<ng-container *ngIf="!cached">
<img
*ngIf="!error"
[hidden]="!loaded"
[src]="src"
[alt]="alt"
(load)="onLoad()"
(error)="onError()"
>
<img
*ngIf="default && (error || !loaded)"
[src]="default"
[alt]="alt"
>
</ng-container>
<ng-container *ngIf="cached">
<img
*ngIf="!error"
[src]="src"
[alt]="alt"
(error)="onError()"
>
<img
*ngIf="default && error"
[src]="default"
[alt]="alt"
>
</ng-container>
Then you can use it like:
然后你可以像这样使用它:
<my-img [src]="src" [alt]="alt" [default]="DEFAULT_IMAGE"></my-img>
PS: I verify beforehand if the image is cached to avoid the image blinking (normally when a component that has the image inside is re-rendered) between the placeholder and the image (if it is cached, I show the image even before the loaded flag be set to true). You can uncomment the log in the isCached
function to see if your images are cached or not.
PS:我事先验证图像是否被缓存以避免图像在占位符和图像之间闪烁(通常当包含图像的组件被重新渲染时)(如果它被缓存,我什至在加载之前显示图像标志设置为真)。您可以在isCached
函数中取消注释日志以查看您的图像是否已缓存。
回答by Omar
The following approach also works if you want to handle the error in you class:
如果您想处理类中的错误,以下方法也适用:
In your template:
在您的模板中:
<img [src]='varWithPath' (error) ="onImgError($event)">
In your class:
在你的课堂上:
onImgError(event) {
event.target.src = 'assets/path_to_your_placeholder_image.jpg';
}
回答by micronyks
<img class="thumbnail-image" src="getImage()" alt="...">
getImage():string{ //I don't know how would you handle your situation here. But you can think of it.
if (this.validImage) // I don't know how would you manage validImage here.
{
return this.validImagePath;
}
return this.placeholderImagePath;
}
回答by robert king
src="validImage ? validImageUrl : placeHolderImgUrl"
回答by Jared Josafhat H Z
I Just did this :
我只是这样做:
In my HTML FILE wrote this
在我的 HTML FILE 中写了这个
<div
(click)="getInfo(results[movie].id)"
*ngFor="let movie of (results | key:'10')"
class="card" style="margin-top:7%;">
<img [src]="getImage(results[movie])" alt="" class="card-img-top pointer"></div>
I called a function that is in my component.ts and pass the object wheres my url as a parameter
我调用了我的 component.ts 中的一个函数,并传递了我的 url 作为参数的对象
getImage(result){
if(result.poster_path){
return this.imageURL+(result.poster_path);
}else return "./assets/noFound.jpg"
Heres my function , first I verify if the object image url is different from null if is true then I return the image url else i return my default "noFound" image that is in my app assets.
Hope it helps!
这是我的函数,首先我验证对象图像 url 是否不同于 null 如果为 true 然后我返回图像 url 否则我返回我的应用程序资产中的默认“noFound”图像。
希望能帮助到你!