7

I need to check if a image exists in the folder using Angular 4.I have a list of image name that is returned from the server. What I need is to check if that image exists in the asset folder. Any help or idea would be great.

3
  • name are same or different names?? Commented Nov 14, 2017 at 10:03
  • what do u mean? i need to check if the image exists in the folder by name Commented Nov 14, 2017 at 10:04
  • Is it relative or absolute path? Commented Nov 14, 2017 at 10:54

2 Answers 2

11

Try this. Answer found on link

// The "callback" argument is called with either true or false
// depending on whether the image at "url" exists or not.
function imageExists(url, callback) {
  var img = new Image();
  img.onload = function() { callback(true); };
  img.onerror = function() { callback(false); };
  img.src = url;
}

// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
  console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});

I would like to warn you. Becareful with it, It can run you to performance issue for checking more images at once due to it's loading images to memory if exists.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

imageExists(itemId) {
    let img = new Image();
    img.src = 'assets/menu_image/'+itemId+'.jpg';
    if (img.complete){
        return 'assets/menu_image/'+itemId+'.jpg'
    }else {
        return 'assets/logo-white.png'
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.