What could be causing the repetitive output in an Angular click event loop?

I am facing an issue while trying to log the data of the user based on the user tab that has been clicked. The problem is that it always displays the same data and not the data of other users.

https://i.sstatic.net/ACo7y.png

For example, when I click on Sara, it shows Sara's data. However, when I click on Edita, it still displays Sara's data. I need assistance on how to retrieve the data based on the user tab that has been clicked.

ts file

response: Array<any> = [];

getUsers(){
    this.http.get('https://dummyapi.io/data/v1/user', {
      headers: new HttpHeaders().set('app-id', '63a1a3fdf4c5089b8564caef'),
      params: new HttpParams().set('limit', '50')
    }).subscribe(data => {
      
      this.response.push(data);

    }), ((error: object) => {
      console.log(error)
    })
  }

 showChat(){
    for(let i=0; i<this.response.length; i++){
      console.log(this.response[0].data[i])
    }
  }

html file

<div class="user-bottom">
        <div class="all-users" *ngFor="let array of response" (click)="showChat()" >
            <div class="nested-items" *ngFor="let data of array.data">
                <h4>{{data.firstName}}</h4>&nbsp;
                <img src="{{data.picture}}" alt="profile">
            </div>
        </div>
    </div>

Answer №1

Something seems off here.

The response variable seems to only have one element, causing your for loop in the showChat() function to only run once.

It appears that your click listener is attached to the parent element rather than each individual child element.

To make things work properly, consider using a template like this:

<div class="user-bottom">
  <div class="all-users" *ngFor="let array of response">
    <div class="nested-items" *ngFor="let data of array.data; let i = index;" (click)="showChat(i)">
      <h4>{{data.firstName}}</h4>&nbsp;
      <img src="{{data.picture}}" alt="profile">
    </div>
  </div>
</div>

You may need to adjust your method to something like this:

showChat(i: number) {
  console.log(this.response[0][i]);
}

Does that explanation help clarify things?

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

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

Grails: Javascript function for updating the image source is unresponsive

I have a situation where I need to change the src of an img based on a certain condition. The condition is returning true as expected, as confirmed by an alert() that I added previously. However, the function responsible for changing the src of the img and ...

mvc and ajax - failing to access model attributes

I'm encountering an issue where the inputs in my beginform are not being auto-posted successfully. Their values do not reach the model or controller and remain null (breakpoints are never hit). What could possibly be causing this? @model project.Mo ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

The issue arises when trying to set the height of the modal body correctly while using ng-bootstrap to open the modal as a separate component

There seems to be an issue with the height not being properly added in the modal body when the modal is opened as a separate component using ng-bootstrap. The problem can be seen in the following link: https://i.sstatic.net/natkn.png https://stackblitz.co ...

Slider Carousel for Multiple Items: Horizontal Orientation

I attempted to create a multi-item carousel slider using Bootstrap and found some code online to help me. However, the code is not functioning correctly. The issue is that the cards are not displaying next to each other horizontally as they should. Unfortu ...

Three.js- I am having trouble with my shadow rendering, as lots of black lines are appearing everywhere instead of the shadows showing

Having recently delved into Three.js, I managed to add shadows to my model with the help of some knowledgeable individuals. However, upon the light hitting the model, numerous lines appear, causing me to question whether it's due to my poor modeling s ...

Issue with Jquery .ajax function returning an object even after it has already moved on to the next line of code

I'm currently working with JQUERY and AJAX, and it seems like the function is somewhat functional but there's a glitch that occurs after the next line of code runs. This issue causes the script to add a null value when trying to insert the object ...

Is there a way to have content update automatically?

After writing this block of code, I discovered that clicking on one of the circles activates it and displays the corresponding content. Now, I am looking for a way to automate this process so that every 5 seconds, a new circle gets activated along with its ...

Having trouble deleting a component from an array in React?

I am facing an issue with my array and component functions. Each component has a handleRemove function that is supposed to remove the selected component from the array. However, the function is not working as expected. Instead of deleting just the selected ...

Issue encountered when attempting to convert Angular application to Angular Universal

While attempting to convert my Angular App into Angular Universal, I encountered an issue. I used the command "ng add @nguniversal/express-engine --clientProject my-app" An error occurred: Module not found - '@schematics/angular/utility/json-file&apo ...

Using Jquery to insert content into HTML using the .html() method is not possible

I am inserting Dynamic Code into a Div via Ajax and I also need to include some Javascript, but it's not displaying in the code. Below is the code snippet: $.ajax({ url: "ajax_add_logo_parts.php", data: 'act=getPartIm ...

Measure the loading times of external web pages using JavaScript

I am seeking a minimalist approach to create a webpage on my server that utilizes JavaScript to calculate the loading time of the login page on various remote URLs/servers. These servers are dispersed globally, and my aim is to determine the quickest one f ...

Retrieve all populated fields on the second tier using Node.js and Mongoose

Do you have any insights to share on Node.js and mongoose? I've defined a mongoose schema and when I use findOne(), it returns a document with multiple elements under the "resource" key. Below is an example of how the document looks like: { "met ...

Using the ngFor directive, parent and child components can establish communication even with empty arrays

I am working on passing data from a parent component to a child component using the ngFor directive. However, I am facing an issue when some arrays have no length, as I need to indicate to the child component that the array is empty. How can I achieve this ...

Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to functi ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Utilizing the current state within a React callback function closure: A guide to maximising efficiency

I'm currently working on a web page that features a dynamic list of form inputs. Users have the ability to add or remove input fields using designated buttons. To manage this functionality, I've created a parent object called <Ingredients /> ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...