Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2: Loop through list of objects

I am trying to create a view that displays a list of clients and I'm running into an issue due to the fact that it's an object and because of Ionic's html types.

Here is my object:

x = { Consultation: [{name: "Joe Smith}, {name: "Jane Doe"}],
   Re-evaluation: [{name: "Joe Smith2}, {name: "Jane Doe2"}],
   Meeting: [{name: "Joe Smith3}, {name: "Jane Doe3"}],
   Testing: [{name: "Joe Smith4}, {name: "Jane Doe4"}]
}

and I define appointment_types as Object.keys(x) aka ["Consultation", "Re-evaluation", "Meeting", "Testing"].

In my view:

<ion-list>
  <ion-list-header *ngFor="let type of appointment_types">{{ type }}</ion-list-header>

  <!-- type is no longer defined after ion-list-header closes -->
  <ion-item-sliding class="shaded-slider" *ngFor="let client of appointment_types[type]"> 
    <ion-item>{{ client.name }}</ion-item>
  </ion-item-sliding>
</ion-list>

Is there something I can do to stay inside the appointment_types loop?

like image 992
Jeremy Thomas Avatar asked May 23 '17 21:05

Jeremy Thomas


1 Answers

You can solve this by having your iteration of the type in ion-list:

<ion-list *ngFor="let type of appointment_types">

and then when you have the type and your original object x, you can iterate the x object with inner arrays like:

<ion-item-sliding class="shaded-slider" *ngFor="let client of x[type]"> 

So your complete template would look like this:

<ion-list *ngFor="let type of appointment_types">
  <ion-list-header >{{ type }}</ion-list-header>
  <ion-item-sliding class="shaded-slider" *ngFor="let client of x[type]"> 
    <ion-item>{{ client.name }}</ion-item>
  </ion-item-sliding>
</ion-list>

Here's a PLUNKER

like image 80
AT82 Avatar answered Nov 07 '22 16:11

AT82