Search code examples
angulartypescriptangular17

Angular 17 - How I create some loading inside a for loop?


I have a website that is a Video Gallery of my Youtube, and this videos are builded in iframe tag. But I want use some loading in this for loop, because when I open my page the load is slow. What I do?

My Code:

`@for (link of youtubeLinks; track $index) {
    <div class="video-container mx-1 mb-2">
      <iframe #youtubeVideos 
              width="315" 
              height="560" 
              [src]="getVideoSrc(link)" 
              frameborder="0" 
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
               allowfullscreen>
       </iframe>
    </div>
 }`

I used a @defer directive, but doesn't worked.

I wanted each iframe to be loaded as the page scrolled, or to each one to be loaded at a time, not all of them as soon as they entered the page.


Solution

  • You can use @defer, but if you read the docs carefully you will notice

    A type of block that can be used to defer load the JavaScript for components, directives and pipes used inside a component template.

    Your iframe element doesnt match this description. So what you should do is to move iframe to a separate component and then use @defer to wrap your component

        @defer (on viewport) {
          <app-video [src]="link" [width]="width" [height]="height"/>
        }
        @placeholder { 
          <div [style.width.px]="width" [style.height.px]="height">Loading...</div>
        }
    

    it's important to make placeholder size of your iframe because otherwise all of your video placeholder will be on viewport which will cause every video to load right away. So you should reserve place on page via placeholder fixed sizes equal to iframes.

    This way when you open the page you'll see placeholder at first, angular then sees that first placeholder is on viewport which gonna trigger first component to load, then when you scroll to 2nd one - same scenario applies etc.

    Result: https://stackblitz.com/edit/stackblitz-starters-y1wozs?file=src%2Fmain.ts