Modify the DOM at a later time once the images have loaded. This particular action is being executed within the context of an

main.ts


myFunction(){
   this.service.getData().subscribe(
            response => {
                this.handleData(response);
            },
            error => console.log(error),
            () => console.log('request done')
          );
}

handleData(data: DataModel[]) {
     forEach(data, async (item: DataModel) => {

     // Perform some operations here
     const apiResponse: APIResponse = await this.apiService.fetchData(item.endpoint); 

      const modifiedItem: DataModel = {
          property: item.property,
          value: this.customMethod(apiResponse.data)
        };

        switch (modifiedItem.property) {
          case PropertyEnum.A: {
            this.listA.push(modifiedItem);
            break;
          }
          case PropertyEnum.B: {
            this.listB.push(modifiedItem);
            break;
          }
          default:
        }
       });
    });
  }

main.html

 <div *ngFor="let item of listA">
  <p>
    {{item.value}}
  </p>
</div>

It is evident that the current code structure may result in performance drawbacks. For example, making multiple server calls for each item can impact efficiency. How can we enhance the architecture to address such issues?

Is it possible to delay loading images until after other content has been displayed? Would incorporating a library like ng-lazyload-image be beneficial in this scenario? Given the dynamic nature of the data, how can we efficiently handle image retrieval and display within a loop?

An option could involve utilizing Promise.all to fetch all images at once. Yet, updating the DOM specifically for these images remains a challenge. Any suggestions on a more optimized approach to tackle this situation?

What strategies would you recommend for redesigning the solution to better accommodate the requirements?

Answer №1

Suppose you are dealing with a scenario where there are 100 events, each requiring an image to be loaded. Loading all these images at once can strain the client's resources.

Luckily, you have a couple of options:

  1. Utilize the native loading="lazy" attribute introduced in Chrome 75.
  2. Employ the IntersectionObserver API to determine if an element is visible in the viewport and load the associated img accordingly.

This approach ensures that only a few images are initially downloaded during the first load, with additional images being fetched as the user scrolls down.


By the way, when handling subscriptions, it's advisable to do so in the view (using the async pipe) rather than the component itself. Here's an example:

userEvents$ = this.eventService.getUserEvents(uid)
  .pipe(
    tap(response => this.setEvents(response)),
    catchError(error => console.error(error)),
    tap(() => console.log('done'));

In the view, you can simply use:

<ng-container *ngIf="userEvents$ | async as userEvents">
  <!-- Angular will handle automatic unsubscription when this component is destroyed -->
</ng-container>

By following this pattern, you prevent memory leaks as Angular automatically unsubscribes from observables.

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

An issue has arisen: It seems that properties of null cannot be accessed, particularly the 'toISOString' property

After upgrading the dependencies in my package.json to their latest versions, I encountered an error while accessing a page that calls this data. Given that the dependencies were outdated by at least 2 years or more, I suspect the issue lies with the updat ...

Disoriented InstancedMeshes causing confusion in THREE JS

Currently, I am experimenting with terrain generation code to generate water at a specific Y level and stone at another. This is just a preliminary model for my upcoming project on Minecraft terrain generation. However, I've encountered a problem wher ...

The use of $scope.$destroy may resolve memory leak issues, but it can also cause

In my TypeScript AngularJS application, I have a child directive that is dynamically generated. The template and controller are assigned at runtime based on the requirements of the situation, with multiple directives within the template. To display multipl ...

The jQuery script is malfunctioning

I have implemented an order form where users must complete a captcha code verification for cash on delivery. I am using jQuery to validate the entered captcha code. If the entered captcha code is incorrect, I prevent the user from submitting the form and ...

Utilizing Django to access a JavaScript variable within server-side template code

I am faced with a challenge on a page that dynamically adds textboxes. In order to access the relevant context variable within these dynamically added text boxes, I need to utilize the 'i' variable in both my javascript and template code. Specifi ...

``What is the process for retrieving an object array that has been stored in a session using

I have a new class definition: class ProductDetails { name!: string; price!: number; } I keep an array of these objects in the local storage like this: productList: Array<ProductDetails> = []; ... ... localStorage.setItem("CurrentProducts ...

Resolve problems with implementing dynamic routes in Next.js

I have been learning about Next.js and I am struggling with understanding how to set up dynamic routing. I have the following setup: https://i.stack.imgur.com/uBPdm.png https://i.stack.imgur.com/YYSxn.png "use client" import React from "reac ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Focusing in on the mouse location to magnify a THREE.js element

I am currently working on a project using THREE.js and I have encountered an issue with zooming the object. The zoom functionality is centered around the render position when using trackball controls, but I need it to be based on the cursor's position ...

Define a module function that can be used externally

I am encountering an issue while trying to declare an external module that does not have existing typings. This library has a function that returns a string and takes no arguments. My attempt to define it in a .d.ts file is as follows: declare module "c ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

What are some cookie serialization techniques in JavaScript and PHP?

I have a form with multiple select options that I want to save in a cookie for user convenience. The goal is to make the serialization of the cookie easily readable in both JavaScript and PHP, allowing me to set the form onLoad and filter search results ba ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

Unable to click on element at specific location

Hey there, I'm encountering an issue trying to click on a specific element and it's not working. I keep receiving the following error message: ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at ...

When working on a MEAN web application, encountering HTTP responses like 403 or 500 from the Express server can sometimes go unnoticed and not be properly handled in the errorCallback function within

Within my Node web app, there is a situation where an HTTP GET request is sent in one of the Angular controllers. At the same route defined in Express, somewhere in the route logic, an HTTP 500 response (also tried 403 Error) is also being sent. However, i ...

Implementing Material-UI’s FlatButton and Dialog in ReactJS for dynamic TableRow functionality

I am working with Material-UI and have implemented a <Table> component. Each dynamically rendered <TableRow> in the <TableBody> needs to include a button (<FlatButton>) within one of the columns. When this button is clicked, a <D ...

ngx-datatable: Exploring the Differences Between PageSize and Limit

Currently in the process of incorporating ng-datatable into my Angular 4 application. I am uncertain about the intended purpose of [limit] and its relationship with pageSize (which is triggered as part of the (page) event). It appears that pageSize depen ...

How can dynamically added data be retained in a table after reloading the page?

I have a piece of JavaScript code that is functioning properly, but the dynamically inserted data in the table gets lost after reloading the page. I am also implementing server-side validation and need to ensure that the dynamically added data persists e ...

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Using canvas to smoothly transition an object from one point to another along a curved path

As a beginner in working with canvas, I am facing a challenge of moving an object from one fixed coordinate to another using an arc. While referring to the code example of a solar system on https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutori ...