How can I incorporate loading animations within a for loop in Angular 17?

I am currently working on a Video Gallery website showcasing my YouTube videos, all embedded using the iframe tag. However, I have been facing slow load times when opening the page. I want to incorporate some form of loading animation or method to improve the loading speed. Any suggestions?

Here is a snippet of 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 have tried using a @defer directive to no avail.

My goal is to load each iframe either as the page is scrolled or one at a time, rather than loading all of them at once upon entering the page.

Answer №1

If you utilize @defer in Angular, it's crucial to carefully read the documentation to understand its purpose.

@defer is a feature designed to delay loading JavaScript for components, directives, and pipes used within a component template.

It's important to note that your iframe element does not align with this functionality. To address this, consider moving the iframe to a separate component and applying @defer appropriately.

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

Ensure the placeholder size matches that of your iframe to prevent all video placeholders from loading at once. This approach reserves space on the page for each iframe.

By following this method, when you navigate to the page, you will first see the placeholder. Angular will then detect the placeholder on viewport, triggering the loading of the respective component. This process repeats as you scroll through the page.

See the end result here: https://stackblitz.com/edit/stackblitz-starters-y1wozs?file=src%2Fmain.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Is it possible to omit the 'children' property when extending an HTMLDivElement in Typescript?

Currently, I have a SplitPane component that has the functionality to adjust the size of the second child to fill the remaining space whenever the first child's size changes. While this implementation works, I am looking to enhance the interface by ad ...

Hostlistener is unresponsive to inputs from arrow keys

Within my Angular 2 component, I have implemented a key event listener to capture keystrokes: @HostListener('document:keypress', ['$event']) handleKeyboardEvent(event: KeyboardEvent) { console.log(event); } Oddly enough, I am not ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

The system encountered an issue: Unable to access the filter property of an undefined property

Here is my form code in TypeScript: this.editForm = this.fb.group({ 'dropoffs': this.fb.array(this.createDropOffFacility(data.dropoffs.filter(picks => picks.drop_facility !== ''))), }); createDropOffFacility(facilities) { ...

Angular 7 encountering issues retrieving HTTP headers

Is it possible to perform web scraping without using Python? I am attempting to make a simple HTTP GET request from a web Angular app, but I am running into an issue with the response. Specifically, I need to access the headers in order to obtain the csrft ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Angular - optimize performance of vm-ware datagrid by using clrDgRefresh with debounce for improved

Is there a way to delay an event triggered by the clarity datagrid until after the user has finished typing before fetching data from the backend? My angular 6 application uses the grid, and I bind the event to a function in my setup like this: <clr-da ...

Issue with passing an Angular or Ionic object to a view

Currently facing an access issue in my home.ts file where I am unable to retrieve object values in home.html using {{detail.ID}} senddata(){ this.httpClient.get('http://queenstshirtdesigner.com/wp-json/posts/'+this.id, { header ...

Modifying the color of the chosen item - ion-select

Can anyone help me with changing the color of the selected item on ion-select? I've tried several solutions without success. Any suggestions? Documentation: https://ionicframework.com/docs/api/select I attempted to use the color property, but it did ...

Utilizing an object's value as a key for a separate object

Here's an overview of my current object structure: import { imageOne, imageTwo } from "./images"; export const imageKeyMap = { "one": imageOne, "two": imageTwo } The definitions for imageOne and imageTwo ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

Tips for customizing components in React-Table by overriding default columns

In a nutshell, I was tasked with developing a table component using react-table. By default, the table uses an input component that allows instant typing when double-clicked. Additionally, I wanted one of the columns in editableCell to use a dropdown. I ...

Breaking down large reducer into smaller reducers

I am currently working on a feature reducer (slice reducer) called animals. My goal is to separate these reducers into categories such as mammals, birds, fishes, and more. Initially, I thought this would be a smooth process using the ActionReducerMap. How ...

Struggling with slow TypeScript compilation?

My current setup involves TypeScript 2.2.1, but I've been facing prolonged compilation times when running tsc. In an attempt to gather more information, I decided to utilize the --diagnostics option. However, I soon discovered that the "Total time" di ...

Sinon fails to mock the provided URL when GET request includes parameters

I am currently working on creating test cases for the services in my Angular application and encountering some challenges. Below is the code snippet for the service: /** * Sends http request to fetch client states and territories available for a specifi ...

Sending information to ng-template in Angular6

I'm new to Angular 6 and I have a query. How can I pass data to an ng-template from ngFor? component.html <tr *ngFor="let user of data"> <td>{{user.id}}</td> <td>{{user.username}}</td> <td>{{user ...

Experimenting with the routerLink directive in Angular 2

Currently, I am in the process of testing routing functionality. As part of this, I have moved my navbar to a separate component called MdNavbar, which primarily consists of HTML and CSS. The RouteConfig is located in another component where MdNavbar is in ...

Mastering the art of Typescript typing

I am attempting to start the REST server for an Aries agent as outlined here: import { startServer } from '@aries-framework/rest' import { Agent } from '@aries-framework/core' import { agentDependencies } from '@aries-framework/nod ...