Angular: Monitor element is in viewport after scrolling

Render DOM only when visible

Allen Kim
Digital-Heart

--

Let’s say you need to display a thousands of images.

<div class=”img-container” *ngFor=”let el of images; let i=index”>
<img src=”https://picsum.photos/600/300?image={{i}}">
</div>

What’s the issue with the above code to display 1000 images?

The problem of the above code is it actually download 1000 images and make it ready to display. When you inspect the network activity, you can actually see it.

Too many DOM elements are loading even though users don’t see those.

What you really want is to download images only when you are able to see those. The following is an Angular idea to do it. *inView only download image only if the image is in viewport.

The right amount of DOM elements, users can see, are loading.
<div class=”img-container” *ngFor=”let el of images; let i=index”>
<img *inView src=”https://picsum.photos/600/300?image={{i}}">
</div>

The trick to do this is to use Angular structural directive, and make it to render only if the img tag…

--

--