Image with loading indicator- Angular

Md Moin
3 min readMar 16, 2019

An angular component to display image with loading feature

Loading…..

A very common issue found in context of working with images was how to ensure the screen doesn’t look blank or blunt till the image has loaded, like in most use cases while the data is being retrieved or loaded we illusion it with the help of a loader which ensures that user knows something is happening & he needs to wait. This is what we want to do with images as well, but why do we need there can be many reasons to display a loader, maybe the image is too large to be downloaded or maybe even the network is on a slower side to load it.

Here, we are now going to resolve this with the help of a custom component.

As we can see with the above code base, we have a component image-with-loading, it takes few inputs

  1. height & width : used to specify the dimensions of image to be displayed
  2. image : specifies the source url of image to be loaded
  3. loader : specifies the loader to be displayed

We have a default loader already specified to it provides the consumer with a flexibility to change the loader for every image they want to load & default height & width dimensions of 200px is marked.

What does this component do, its the hideLoader function which ensures that loader is hidden by setting the state of isLoading to false.

In the html we have a loader image gets loaded in isLoading true state, then we have the actual image to be loaded after that, we are tracking the load & error event to hide the loader. On either side the image needs to be hidden, if you require any add on in case of image fails to load you can refer the below link on how to load alternate images on failure here.

Please note, we are using the ngIf directive to ensure loader gets loaded or hidden based on the state do not make your actual image to be loaded as else part of the ngIf, doing so will never load your actual image & you shall forever see the loader being displayed. You can now use the component as below

one visible issue that was noticed was when image takes longer time to load we do see loader displayed but image also being loaded in chunks, the workaround solution for this would be to hide/show the image using css & make it visible, using the below as we set visibility to hidden & otherwise.

[ngStyle]=”{visibility:isLoading?’hidden’:’’,height:height+’px’,width:width+’px’}”

you can find the full working demo on stackblitz below.

Thanks for reading, please share your views & opinions or if you would like me to explore some unknown scenarios.

--

--

Md Moin

I’m a dev who codes for fun & likes to share my learnings.