Home > database >  Why this loop is showing the same response in angular click event?
Why this loop is showing the same response in angular click event?

Time:01-05

I am trying to log the data of user according to user tab on which we have clicked. But the issue is that it is showing same one data not others.

enter image description here

Like above if I click on Sara it shows me Sara, but when I click on Edita it shows still Sara. Kindly someone help how to achieve the data according to user tab 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 >
        <div  *ngFor="let array of response" (click)="showChat()" >
            <div  *ngFor="let data of array.data">
                <h4>{{data.firstName}}</h4>&nbsp;
                <img src="{{data.picture}}" alt="profile">
            </div>
        </div>
    </div>

CodePudding user response:

There are a few things wrong here.

response only contains one element, so your for loop in showChat() only loops once.

Your click listener is on the parent element, not each separate child element.

With your current setup, you'd want a template along the lines of:

<div >
  <div  *ngFor="let array of response">
    <div  *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>

And your method would change to something like:

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

Does that make sense?

  • Related