Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Check if image url is valid or broken

I am fetching a large number of image URLs from an API and display them in a angular 2 web application. Some of the URLs are broken and i want to replace them with a default picture that is stored locally on my webserver. Does anyone have a suggestion how to test the urls and in the case of status code 404 replace the broken image?

Thanks!

like image 887
Jakob Svenningsson Avatar asked Apr 05 '16 14:04

Jakob Svenningsson


People also ask

How do you check if a URL is a valid image URL?

To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.

How to handle image error in Angular?

In HTML, you can react to broken images at runtime by attaching a handler to the img element's error event. In Angular, you can do this in a directive that you can then simply apply to an img element without any additional code.


2 Answers

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

like image 139
Günter Zöchbauer Avatar answered Oct 13 '22 04:10

Günter Zöchbauer


You can use onError event this way to handle invalid url or broken url.

  • https://plnkr.co/edit/fD8zxd?p=preview
<img [src]="invalidPath" onError="this.src='images/angular.png'"/>  

This way you can directly assign img path to src with onError event

like image 45
Nikhil Shah Avatar answered Oct 13 '22 06:10

Nikhil Shah