0

In my Ionic Angular app, I'm trying to display the below array that contains several workout exercises. Each exercise consits of several sets:

 exercises = [
    {
      name: 'Leg Extension Machine',
      sets: [
        { setNo: 1, reps: 8, weight: 40 },
        { setNo: 2, reps: 10, weight: 36 },
        { setNo: 3, reps: 15, weight: 33 },
      ],
    },
    {
      name: 'Leg Press Machine',
      sets: [
        { setNo: 1, reps: 8, weight: 80 },
        { setNo: 2, reps: 10, weight: 72 },
        { setNo: 3, reps: 15, weight: 65 },
      ],
    },
    {
      name: 'Rear Leg Elevated Split Squat (Bench)',
      sets: [
        { setNo: 1, reps: 8, weight: 8 },
        { setNo: 2, reps: 10, weight: 8 },
        { setNo: 3, reps: 15, weight: 8 },
      ],
    },
  ];

I'm able to use ngFor to display the exercise names like so:

 <ion-card *ngFor="let exercise of exercises">
    <ion-card-header>
      <ion-card-title>
        {{exercise.name}}
      </ion-card-title>
    </ion-card-header>
  </ion-card>

It displays like so:

enter image description here

Now, I am trying to display each set under each Exercise Name.

I've managed to log data related to each set to the console using the below nested loops, but I don't know how to get this data to the front end:

ngOnInit() {
    for (let i = 0; i < this.exercises.length; i++) {
      this.exercises[i].sets;
      console.log('---', this.exercises[i].name);
      for (let x = 0; x < this.exercises[i].sets.length; x++) {
        console.log('---', this.exercises[i].sets[x].weight);
      }
    }
  }
user9847788
  • 2,135
  • 5
  • 31
  • 79

2 Answers2

1

This should work:

<ion-card *ngFor="let exercise of exercises">
    <ion-card-header>
        <ion-card-title>
            {{exercise.name}}
        </ion-card-title>
    </ion-card-header>
    <ion-card-content>
        <div *ngFor="let set of exercise.sets">
            <ul>
                <li><strong>Nr.</strong> {{set.setNo}}</li>
                <li><strong>Reps</strong> {{set.reps}}</li>
                <li><strong>Weight</strong> {{set.weight}}</li>
            </ul>
        </div>
    </ion-card-content>
</ion-card>

You already have the current object of your exercise assigned to exercise so you can then retreive the sets from that variable and iterate over these sets.

itsdev
  • 21
  • 2
1

In the template, you need to use 3 loops and for displaying the individual set by keys and value you need to leverage the keyvalue pipe.

<div *ngFor="let exercise of exercises">
  <h2>{{ exercise.name }}</h2>

  <div *ngFor="let set of exercise.sets">
    <span *ngFor="let prop of set | keyvalue">
      {{ prop.key }}: {{ prop.value }}
    </span>
  </div>
</div>

Here's a stackblitz

ionut-t
  • 1,121
  • 1
  • 7
  • 14