Using Angular, a function can be called recursively directly from within the HTML

I'm struggling with loading an image because the method getUserProfileImage() is getting triggered multiple times within a loop. Is there a way to ensure the method is only called once during each iteration? I understand that this issue is related to Angular's change detection strategy, but how can I effectively address it?

I've done some research on this topic and found several solutions involving hacks to stop change detection strategy, but I prefer not to resort to such workarounds.

    <div *ngFor="let user of listOfContacts">
            <img class="rounded profile-thumbnail ptr" [src]="getUserProfileImage(user.UserName, user.UserId)" id="image-id-{{user.UserId}}" [routerLink]="['/community/userProfile', '0', user.UserId]">
    </div>

getUserProfileImage() method located in ____.ts class

    getUserProfileImage(userName: string, itemId: number){

      let loadImageSub = this.util.getUserProfileImageByUserName(userName).subscribe(contactsObj => {

      let imageUrl = this.toUrl(contactsObj["Images"][0].SrcAttr);
      console.log("contact profile image", imageUrl);
      (<HTMLInputElement>document.getElementById("image-id-" + itemId)).src = imageUrl;
      loadImageSub.unsubscribe();

    });
 }

Error: The same image is being loaded repeatedly, causing recursive function calls. https://i.sstatic.net/xDIFD.png

Answer №1

Avoid calling functions in templates whenever possible, as you have already pointed out yourself. It seems like you are aiming to retrieve all data before rendering the template, ensuring a well-structured data format with images stored within each object for display using ngFor.

If your contacts are being fetched from an API call, consider utilizing forkJoin and switchMap to obtain the image URL for each object. The following example demonstrates fetching all users first, followed by retrieving posts associated with each user and storing them in a posts property within the original user data. Modify this approach according to your use case. Instead of using any, strive to specify data types for clarity.

// Retrieve all users first!
this.getUsers()
  .pipe(
    switchMap((data: any) => {
      // For each user, fetch their posts and combine with original user data
      return forkJoin(
        data.map((user: any) =>
          this.getPosts(user.id).pipe(map((postData) => ({ ...user, posts: postData }))
        )
      );
    })
  )
  .subscribe(data => console.log(data));

In your scenario, apply the same logic within switchMap to use forkjoin on all contact person images, attaching them to a property in your contact object instead of posts as demonstrated in the sample code above :)

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

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

What could be causing the OnInit lifecycle hook to fail to execute properly?

I'm having trouble with this code. Every time I run it, the console throws a type error saying it can't read property sort. Does anyone have any ideas on how to fix this? import { Component, OnInit, Input } from '@angular/core'; impor ...

Validating emails using angular material chips

I'm currently working on implementing a form that utilizes input chips to facilitate sending messages to multiple email addresses. While I've made progress in making the form functional, I'm facing difficulties in displaying error messages w ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

The type 'MockStoreEnhanced<unknown, {}>' is not compatible with the type 'IntrinsicAttributes & Pick[...]

I'm currently working on creating a unit test for a container in TypeScript. From what I've gathered from various responses, it's recommended to use a mock store and pass it to the container using the store attribute. This method seems to o ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

What is the proper method for transferring a JWT token to an external URL?

I currently have two REST endpoints set up: accounts.mydomain.com/login - This is an identity provider that sends a JWT token as a response once a user is authenticated with their username and password. api.mydomain.com/users - This endpoint accepts the ...

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

Angular2, multi-functional overlay element that can be integrated with all components throughout the application

These are the two components I have: overlay @Component({ selector: 'overlay', template: '<div class="check"><ng-content></ng-content></div>' }) export class Overlay { save(params) { //bunch ...

Got a value of `false` for an attribute `closable` that is not meant to be a

Here's the code snippet I have: import { Modal } from "antd"; import styled from "styled-components"; export const StANTModal = styled(Modal)` & .ant-modal-content { border-radius: 20px; overflow: hidden; } `; And ...

What is the best way to send a confidential string from my Node.js backend to my Angular frontend without it being visible to the user?

Currently, I'm working on a project that involves Front-end development with Angular and Back-end with NodeJS. In the backend, I compile Angular static files using the command: response.sendFile(path.join(__dirname, 'dirname', 'index.h ...

Discover how to access and manipulate JSON files in an Angular application using

Currently, I am diving into learning TypeScript with Angular and I'm interested in reading a JSON file. The structure of my JSON file is as follows: { "nb": "7", "extport": "1176",, "REQ_EMAIL": ...

Encountering an issue while constructing an Angular library project. The 'ng serve' command runs smoothly on local environment, but an error message stating

I recently developed an npm package called Cloudee. While it functions perfectly locally, I encounter an issue when attempting to deploy it. The error message states: 'Unexpected value 'CloudyModule in /home/hadi/dev/rickithadi/node_modules/cloud ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Creating ngModel dynamically with *ngFor in Angular 2: A guide

I've been struggling with this for the past couple of days - how can I have a new ngModel for each iteration within an *ngFor loop? The idea is that I load a list of questions, and within each question there are 2 propositions. Here's the HTML: & ...

Strategies for Resolving Angular Unsupported Engines Alert

I've encountered issues in my Angular project with Unsupported Engines errors such as: npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@angular-devkit/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Achieve flattening of types using recursion in TypeScript with the help of const

I am presenting the TypeScript code below: type Item = { key: number; value: string; items?: readonly Item[]; } const items = [ { key: 1, value: 'foo', items: [{ key: 3, value: 'baz' }] }, { key: 2, value: 'bar ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...