What is the best way to access individual items within an *ngFor loop in Angular?

Is it possible to retrieve the value of item.profile image and utilize it in the update function shown in the code below?

<ion-content>
        <ion-grid style ="text-align: center">
         <ion-row class="ion-align-items-center" >
        <ion-col class="ion-align-items-center" *ngFor="let item of students" >
          <ion-avatar class="ion-align-items-center">
                <ion-img [src] = "item.profileImage"></ion-img>
              </ion-avatar>
        </ion-col>  
       </ion-row>
         <ion-row  style ="text-align: center">  
           <ion-col>
             <ion-button  size="small" fill="outline" (click)="chooseProfilePic()" >Choose Profile Photo</ion-button>
           </ion-col>
        </ion-row>
       </ion-grid>

Why does using this.item.profileImage as a value result in an undefined error in the console?

export class EditProfilePage implements OnInit {

  item: any

    this.profileImage =  "./assets/imgs/user.png" || this.item.profileImage;
    this.profileService.read_Students().subscribe(data => {

      this.students = data.map(e => {
        return {
          id: e.payload.doc.id,
          isEdit: false,
          userName: e.payload.doc.data()['userName'],
          userBio: e.payload.doc.data()['userBio'],
          profileImage: e.payload.doc.data()['profileImage'],
        };
      })
      console.log(this.students);


  UpdateRecord(recordRow) {
    let record = {};
    record['userName'] = recordRow.userName || "" ;
    record['profileImage'] = this.item.profileImage;
    record['userBio'] = recordRow.userBio || "" ;
    this.profileService.update_Student(recordRow.id, record);
    recordRow.isEdit = false;
  }

Answer №1

Utilize the index within your loop to access the item using the index parameter in the function. Include index as a parameter in the chooseProfilePic(i) function:

<ion-grid style="text-align: center">
    <ion-row class="ion-align-items-center">
        <ion-col class="ion-align-items-center" *ngFor="let item of students; let i = index">
            <ion-avatar class="ion-align-items-center">
                <ion-img [src]="item.profileImage"></ion-img>
            </ion-avatar>
        </ion-col>
    </ion-row>
    <ion-row style="text-align: center">
        <ion-col>
            <ion-button size="small" fill="outline" (click)="chooseProfilePic(i)">Choose Profile Photo</ion-button>
        </ion-col>
    </ion-row>
</ion-grid>

Retrieve the item in the function logic:

chooseProfilePic(i) { 
  this.item = students[i]; // get item
  const profileImage = students[i].profileImage
}

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

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

The issue is being caused by a missing package.json file in the current directory, even though it

Hello, I've encountered an error message while attempting to install packages using npm install with the command npm install "package name": npm ERR! path C:\Users\abecker\Documents\Git-ng2-Admin\file:..\has-unicode&bsol ...

Expecting a return value from CreateAsyncThunk

I need help converting the following JavaScript code to TypeScript. I keep running into an error message that says Expected to return a value at the end of async arrow function. Can someone help me figure out what's wrong with this code? export const ...

Mastering the Art of Utilizing Generic Typing to Access Objects

I am trying to find a way to access an object by class using generic typing. The issue I am encountering is that I am getting an error when trying to check if the locators contain an input field. type '{ form1: { item2: { checkbox: string; input: st ...

Reacting like sticky bottoms and tops

I'm working on a react/tailwind project that involves a component I want to be fixed at both the top and bottom of the screen. In simpler terms, there's an element that I need to always stay visible even when the user scrolls up or down the page ...

The absence of a scroll bar on the web application is preventing me from scrolling properly

The vertical scroll bar on my Angular app seems to have disappeared mysteriously. I haven't made any changes to the code recently, and I'm struggling to figure out why it's missing. I've spent days trying to troubleshoot this issue with ...

Creating an Angular Accordion/Zippy Component: A Step-by-Step Guide

I am currently tackling a project involving the presentation of a list of grievances in a zippy/accordion format. The data set I work with is an array of key-value pairs found in my component.ts file, shown below: isExpanded: boolean; complaints: any[] = ...

Combining objects in JavaScript

I am currently working on converting the object received from the server into a format compatible with the backend system. I have a received object that looks like this { 'User.permissions.user.view.dashboard': true, 'Admin.permissio ...

Interface in React Typescript does not include the specified property

Just starting out with React after some previous experience with Angular. I've been trying to create a component that accepts a data model or object as a parameter. Here's what I have: import react from 'react' interface SmbListItem{ ...

Utilizing Business Logic in a MEAN Stack Environment

When developing an Angular application, where should the calculations take place - on the front end or back end? Considering that the outputs need to update with each input change, is it practical to send a request to the back end every time there is an ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Encountering a 504 Gateway Timeout error while attempting to send a POST request to an API route in a NEXT.JS application that

I encountered a 504 error gateway timeout when attempting to post a request to api/webhooks, and in the Vercel log, I received a Task timed out after 10.02 seconds message. This code represents a webhook connection between my clerk and MongoDB. [POST] [m ...

Implementing TypeScript in React FlatList

While TypeScript is a powerful tool, sometimes it feels like I'm working more for TypeScript than it's working for me at the moment. I'm currently using a FlatList to display restaurant results in a Carousel. const renderRestaurantRows = ( ...

The close button on Mat Dialog boxes is unresponsive on IOS devices

I am currently utilizing Angular 13 in my application and have implemented the angular-material Mat-Dialog box as a pop-up modal. Below is the snippet of HTML code for the submit and close buttons: <mat-dialog-actions> <button class="btn" ...

Akita and Angular Error Exploration: Analyzing the StaticInjector and NullInjector in the Context of Store and

I encountered an issue with the Akita state management implementation while working on an Angular project. Here is a brief solution to help others who may face the same problem. The documentation and examples provided by Akita do not offer a clear explana ...

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

Angular Material: Setting the Sidenav/Drawer to Automatically Open by Default

I am currently utilizing the Angular Material Sidenav component within my project. Upon serving the webpage, I encounter an issue where the sidebar is not visible initially (as shown in the first image). However, after resizing the browser window for som ...

What is the best way to utilize await in promises instead of using then?

How can I correctly handle the Promise.all() method? I'm experiencing issues with resolving the promise that generates a series of asynchronous requests (simple database queries in supabase-pg SQL). After iterating through the results with a forEach l ...

Troubleshooting the issue of Child redirect in Angular4 Routing not functioning

My Angular4 routing setup looks like this: {path: 'siteroot', component: SiteMessengerComponent}, { path: '', component: FrameDefaultComponent, children: [ { path: 'user/:userId', component: SiteUs ...