Angular2: Show placeholder image if img src is not valid
The best way to handle broken image links is the use the onError
event for the <img>
tag:
<img class="thumbnail-image" src="./app/assets/images/{{image.ID}}.jpg"
onerror="this.src='./app/assets/images/placeholder.jpg';" alt="..." />
Angular 2 - Check if image url is valid or broken
Listen to the error
event of the image element:
<img [src]="someUrl" (error)="updateUrl($event)">
where updateUrl(event) { ... }
assigns a new value to this.someUrl
.
Plunker example
If you want to check in code only you can use the method explained in Checking if image does exists using javascript
@Directive({
selector: 'img[default]',
host: {
'(error)':'updateUrl()',
'[src]':'src'
}
})
class DefaultImage {
@Input() src:string;
@Input() default:string;
updateUrl() {
this.src = this.default;
}
}
Directive Plunker example
Don't display an image that's not found in Angular
Thanks to discovering the (error)
event I managed to think of a simple solution by tracking the index and splicing out the path. That way, the image tag simply won't be added.
<div class="gallery-img" gallerize>
<ng-container *ngFor="let p of dynamicPaths; let i = index">
<img src="{{p}}" (error)="dynamicPaths.splice(i, 1)">
</ng-container>
</div>
angular2 onError image binding
It was almost complete he just forgot to change the image after the event.
errorHandler(event) {
console.debug(event);
event.target.src = "https://cdn.browshot.com/static/images/not-found.png";
}
Here is the
link
Set placeholder image if tag does not exist ionic 2 angular 2
You can use *ngif
. example:
<img *ngIf="entry.getElementsByTagName('enclosure')[0].getAttribute('url')" class="imgmg" src="{{entry.getElementsByTagName('enclosure')[0].getAttribute('url')}}">
<img *ngIf="!entry.getElementsByTagName('enclosure')[0].getAttribute('url')" class="imgmg" src="assets/images/placeholder_image.png">
also check this link
EDIT:
<img *ngIf="image_available" class="imgmg" src="{{entry.getElementsByTagName('enclosure')[0].getAttribute('url')}}">
<img *ngIf="!image_available" class="imgmg" src="assets/images/placeholder_image.png">
Inputting a default image in case the src attribute of an html <img> is not valid?
You asked for an HTML only solution...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head> <title>Object Test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body>
<p> <object data="http://stackoverflow.com/does-not-exist.png" type="image/png"> <img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45" alt="Stack Overflow logo and icons and such"> </object> </p>
</body>
</html>
Angular7: Show placeholder image on loading
You can use the Image object along with the onload event, which triggers when the image is loaded by the browser
let imgIsLoaded = false; const img = new Image(250, 250); img.src = 'mypath.jpg'; img.onload(() => { imgIsLoaded = true; });
img.isLoading { background-color: rgb(150, 150, 150)}
<img src="mypath.jpg" [class.isLoading]="!imgIsLoaded">
How to gently change img src in Angular2+
I hacked around a little with your stackblitz demo, I basically wrapped your code in an ImageGhostDirective
to make it reusable. The directive listens to any changes on the src
attribute using a MutationObserver
to change the style. Using a HostListener
on the 'load' event, it reverts the styles back to normal. I start with an opacity of 0 for the first load, followed by an opacity of 0.2 between successive image changes, but this is completely arbitrary and could be replaced by a spinner or any kind of placeholder...
Here is the link to the stackblitz: https://stackblitz.com/edit/angular-image-ghost-directive
<img [src]="'https://loremflickr.com/300/300?random=' + index"
style="width: 300px; height: 300px" imgGhost>
@Directive({
selector: 'img[imgGhost]'
})
export class ImageGhostDirective implements OnDestroy {
private changes: MutationObserver;
constructor(private elementRef: ElementRef) {
this.changes = new MutationObserver((mutations: MutationRecord[]) =>
mutations.filter(m => m.attributeName === 'src').forEach(() => this.opacity = 0.2)
);
this.changes.observe(this.elementRef.nativeElement, {
attributes: true,
childList: false,
characterData: false
});
}
ngOnDestroy(): void {
this.changes.disconnect();
}
@HostBinding('style.display') display = 'block';
@HostBinding('style.opacity') opacity = 0;
@HostListener('load')
onLoad(): void {
this.opacity = 1;
}
}
It is also possible to tell Angular to automatically attach this directive to every img
element by using the img:not([imgGhost])
selector in the directive decorator. That way, you don't have to manually place the directive on every image in your app.
Hope this is useful.
Related Topics
How to Combine First Name and Last Name in JavaScript
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
How to Make a Owl Carousel With Arrows Instead of Next Previous
Calculate Percentage JavaScript
How to Refresh Select Option List After Ajax Response
How to Read Data from *.Csv File Using JavaScript
Uncheck a Checkbox and Another Checkbox Will Untick
How to Make an Area Unclickable With CSS
Angular 4: Cannot Instantiate Cyclic Dependency! Injectiontoken_Http_Interceptors
How to Import Modules from All Files in a Directory, Using a Wildcard
How to Get the Contextpath from Javascript, the Right Way
Reprompt for Permissions With Getusermedia() After Initial Denial
Jquery Wait Until Ajax Call Has Got Data Before Displaying
How to Toggle (Hide/Show) Sidebar Div Using Jquery
Get Selected Item Value from Bootstrap Dropdown With Specific Id
Add and Remove Values Inside Array in Change Event of Checkbox
Uncaught (In Promise) Typeerror: Failed to Fetch and Cors Error