Please place the accurate image inside the designated box based on the corresponding ID number

I am currently working on a function that retrieves image data from a database and displays it in HTML using *ngFor directive.

In order to display the correct image, I need to fetch the ID associated with the image data and use it to retrieve the corresponding image.

Although I am able to retrieve all the IDs and images successfully, when I try to preview them, all the images appear to be the same across different boxes. This means that if there are 10 images, all 10 will be loaded but only the last one will be visible in every box.

The main objective is to display each image in its respective box based on its unique ID.

Would appreciate any assistance in resolving this issue.

My HTML

<div class="row tab-pane Galeria">
            <div *ngFor="let product of products" class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
              <div class="image-item" (click)="fillModal($event, product)">
                  <a class="d-block image-block h-100">
                  <homeImage> 
                        <img *ngIf="Images && Images[product.id] && inView" [src]="Images" class="Images img-fluid" alt="">                  
                  </homeImage> 
                  </a>           
                <div class="ImageText">{{product.name}}</div>
              </div>
            </div>
          </div>

Component.ts

  GetProducts() {
    let self = this;
    this.Global.refreshToken()
      .subscribe(function (result) {
        self.homeService.getProducts()
          .then(function (resultado) {
            if (resultado) {
              self.products = resultado;
            }
          })
          .then(() => {
            if (self.products) {
              return Promise.all(self.products.map((product) => self.ImageInfo(product.id)));
            }
          })
          .catch((err) => console.error(err));
      });
  }

  ImageInfo(id) {
    var self = this;
    this.Global.refreshToken().subscribe(function (result) {
      self.homeService.getImage(id).then(function (resultado) {
        if (resultado) {
          self.Images=resultado;
        }
      }).catch();
    });
  }

Answer №1

It is important to note that the last image displayed will be based on the values assigned in each iteration of products. This means that the final product image shown will be determined by the value of Images after all iterations have been completed.

Mapping Images to Product IDs

 imagMap: Map<string, string> = new Map<string, string>(); 

 You can then use this mapping in [src]="imagMap.get(product.id)" 

As for the image service:

 ImageInfo(id) {
var self = this;
this.Global.refreshToken().subscribe(function (result) {
  self.homeService.getImage(id).then(function (resultado) {
    if (resultado) {
      self.Images=resultado;
      self.imagMap.set(id,resultado);
    }
  }).catch();
});

}

This approach allows you to track and store every individual image effectively.

Answer №2

Check out this HTML code snippet below. Ensure that the variable image[product.id] is present in your data source.

<div class="row tab-pane Galeria">
        <div *ngFor="let product of products" class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
          <div class="image-item" (click)="fillModal($event, product)">
              <a class="d-block image-block h-100">
              <homeImage> 
                    <img *ngIf="product.images && product.images[product.id] && inView" **src=getImageUrl(product.id)** class="Images img-fluid" alt="">                  
              </homeImage> 
              </a>           
            <div class="ImageText">{{product.name}}</div>
          </div>
        </div>
      </div>

component.ts

 getImageUrl(id){
  this.homeservice.getimageurl(id).......... // specify exactly what you need here
 }

Answer №3

Is it recommended to change [src]="Images" to [src]="Images[product.id]"?

Can you explain the organization of the Images data?

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

What is the process for updating npm and node version on Windows operating system?

Currently immersed in a finance project, but embarking on a new one where we are facing a node version issue. Any tips on how to avoid this problem? ...

What are the benefits of using material-ui@next without the need for

Thinking about creating a project using material-ui@next, but trying to avoid using withStyles. However, encountering issues with the draft of TypeScript that includes the decorator @withStyles. This leads to one question - is it possible to use material ...

Encountering Problems when Converting Vue Application from JavaScript to TypeScript with Vue and Typescript

Currently, I am in the process of converting a Vue project from JavaScript to TypeScript without utilizing the class-style syntax. These are the steps I took: I ran: vue add typescript I went through all my .vue files and: Indicated that TypeScript ...

Is it possible to use Angular signals instead of rxJS operators to handle API calls and responses effectively?

Is it feasible to substitute pipe, map, and observable from rxjs operators with Angular signals while efficiently managing API calls and their responses as needed? I attempted to manage API call responses using signals but did not receive quick response t ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Using Angular 2: Implementing Router into myExceptionHandler

Within my app.module.ts, I've set up the following code: @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, HttpModule ], providers: [ ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below: // TODO - mock axios class instance for skipped Test suites describe("dateFilters()", () => { beforeEac ...

Is it possible to nest a component within another component in the latest iteration of Angular2?

Currently in angular2 version (V2.2.0), I am interested in utilizing a component within another component. In the past, we were able to achieve this by using the following code: import { AnotherComponent } from './another-component'; @Componen ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

Tips on retrieving a strongly typed value from a method using Map<string, object>

Having had experience working with C# for a while, I recently ventured into a Node.js project using TypeScript V3.1.6. It was exciting to discover that TypeScript now supports generics, something I thought I would miss from my C# days. In my C# code, I ha ...

What is the counterpart of $.isEmptyObject({}) in Typescript for checking if an object is

Is there a formal method for testing an Object (response from server) to see if it is empty? Currently, I am using jQuery to accomplish this. this.http.post(url, data, {headers: headers}).then( result => { if (!$.isEmptyObject(result ...

Challenges with displaying css/bootstrap classes within angular2

Experiencing difficulties with CSS/Bootstrap integration when displayed in an angular2 component. When attempting to display the CSS and HTML content in the Index.html file (with proper CSS and JS references), everything functions correctly. However, once ...

Combining union types with intersection operators in Typescript

Here's a concept for an event handling system: type EventMap = Record<string, any>; type EventKey<T extends EventMap> = string & keyof T; type EventReceiver<T> = (params: T) => void; interface Emitter<T extends EventMap&g ...

Guidelines for transmitting form information to a web API using Angular

I am currently working on an Angular 6 project where I have a form and a table that retrieves data from a web API. I want to know if it's possible to send the form data to that web API. Here is the code snippet that I have so far: HTML Form: &l ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...