Lazy Loading Image-Slider on Angular

Burakcan Ekici
3 min readMar 14, 2020

--

Here is a sample to make a lazy loading image slider on Angular. With lazy loading, the speed of your website can be increased. Since the images that we want to show in the slider are taken when it is needed, we can avoid taking all images while the slider is loading and increase the efficiency of the website and speed.

The final aspect of our image-slider

Firstly, we create a list that keeps the information about all the images that we will show in app.component.ts file. To generate images, loremflickr.com is used because it presents an API to generate images that are various sizes and keep all source paths in the list.

Then, we create a custom component as image-slider that selector is be-image-slider and it will be described below detailly and start to make a slider. It is called in app.component.html file and gets image list as input.

After finish to explain how to call images, we are starting to develop our image-slider. Its file hierarchy is shown below.

Our image slider's file hierarchy

In image-slider.component.html, there are 2 components.

  • <img> hold the image we want to show.
  • <div> hold the circle that is placed over the image. It is created as much as the count of the image list.

We handle what we will do in image-slider.component.ts separately;

  • We use data as input to get the image list from the parent component that calls itself. Since the list is taken as an input, we initialize the first image in ngOnInit method. On the other hand, we keep fill and empty icon classes to change the circle that placed over the image when it is clicked.
  • We need to set place of the circles that we put over the image. It must be as much as the count of image list so we handle it in ngAfterViewInit method.
  • As you see in image-slider.component.html, there is a method called change. The image source and circle icon are changed in here. With this method, image-slider.component.ts is shown below.

That’s all, we can see that the request was send just one time. Whenever we click one of the other circles, the request was sent unless the image has got before. We checked it on the developer console. As you see the pictures below, when we click the second circle, the request was sent. This situation continued in the third circle.

The source code is available here.

Edit on StackBlitz

--

--

Responses (1)