pri_91
pri_91

Reputation: 79

Displaying data from an JSON array of users after selecting the ID of a User

I want to display a data of users from an array. After selecting a user, from a list of users, respective details should be displayed about it. Below is the code I tried:

 users = USERS; // contains data
 selectedUser: User;

 constructor() { }

 ngOnInit() {
}

onSelect(index): void {
this.selectedUser = index;
}

Below is my HTML file:

      <div class="row">
        <div class="col-4">
          <ul class="menu">
            <div *ngFor="let user of users; let i = index"
              (click)="onSelect(i)">
              <span><b>{{user.id}}</b></span> {{user.name}}
            </div>
          </ul>
        </div>

        <div *ngIf="selectedUser" class="col-8 menu">
          <div><span><b>id: </b></span> {{selectedUser.id}} </div>
          <div><span><b>Name:</b></span> {{selectedUser.name}} </div>
          <div><span><b>Location:</b></span> {{selectedUser.location}} </div> 
        </div>
     </div>

What condition should I give in ngIf in order to display the data

Upvotes: 2

Views: 199

Answers (2)

Dhaval
Dhaval

Reputation: 978

You store index of the user in selectedUser so you can not find all the details in selectedUser

Current behaviour:

onSelect(index): void {
    this.selectedUser = index; //Here index is any number
}

if the index is 4 your this.selectedUser=4 so {{selectedUser.id}} is undefined that's why it's not display anything

you have to save store user in this.selectedUser for getting all data of selected user like

<div class="row">
   <div class="col-4">
      <ul class="menu">
        <div *ngFor="let user of users; let i = index"
          (click)="onSelect(user)">
        </div>
      </ul>
    </div>

onSelect(user): void {
    this.selectedUser = user; // user is current user
}

OR from the current code, you just store user with an index like:

onSelect(index): void {
   this.selectedUser = this.users[index];
}

Upvotes: 0

Pardeep Jain
Pardeep Jain

Reputation: 86790

Code should be like this -

onSelect(index): void {
   this.selectedUser = this.users[index];
}

Right now you are assigning the only index, and trying to fetch data from that variable which is wrong. so try above code. What it'll do is assign relevant data from users array and display in your UI part.

Upvotes: 2

Related Questions