How do I loop through an array of objects that's within an array of objects and display in my HTML using Angular/Ionic?

Viewed 318

I have an interface like so:

export interface SeriesCard {
  type: string,
  imageUrl: string,
  title: string,
  category: string,
  seriesItems: SeriesItems[];
}

My Service already has mocked data and my .ts file looks like:

seriesCard: SeriesCard[];
  title: string = "";

  constructor(private navCtrl: NavController,
              private cardService: CardsService,
              private navExtraService: NavExtrasServiceService) { }

  navigateToPage(seriesItems: SeriesItems) {
    this.navExtraService.setExtras(seriesItems);
    this.navCtrl.navigateForward([`video-component`]);
  }

  ngOnInit() {
    this.seriesCard = this.cardService.getSeriesCardsArray();
    console.log(this.seriesCard);
  }

in my HTML file, I'm doing an *ngFor to loop through my seriesCard like so:

<ion-content>
  <ion-grid class="ion-no-padding">
    <ion-row>
      <ion-col size="12" *ngFor="let cards of seriesCard; let i = index">
        <ion-list class="ion-list-background">
          <ion-item (click)="navigateToPage(cards.seriesItems[i])" class="ion-item-background" lines="none" style="border-bottom: 1px solid #343436;">
            <ion-avatar slot="start">
              <img src="{{cards.seriesItems[i].imageUrl}}" alt="">
            </ion-avatar>
            <ion-label>
              <h2 style="color: #ffffff">{{cards.seriesItems[i].title}}</h2>
              <ion-text class="smaller">{{cards.seriesItems[i].description}}</ion-text>
            </ion-label>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

My issue is that I need to loop through my SeriesItems[] that's within my SeriesCard[] in my HTML. How do I do that? Because currently, in my mock data, I have 2 SeriesCards objects, each with 4 SeriesItems objects. But my *ngFor is only looping twice because it's looping at the top level instead of a level down (SeriesItems[]).

How do I fix this?

I tried adding another *ngFor but it wasn't working quite right.. I appreciate any support.

EDIT: I have already tried a second *ngFor. The HTML that I showed above is supposed to display the # of SeriesItems within a single SeriesCard. In this case, It would show 4 items, not 8!

1 Answers

You need another *ngFor on <ion-item> tag because SeriesItems[] is array.

<ion-item *ngFor="let seriesItem of cards.seriesItems">
    <ion-avatar slot="start">
       <img src="{{seriesItem.imageUrl}}" alt="">
    </ion-avatar>
    <ion-label>
       <h2 style="color: #ffffff">{{seriesItem.title}}</h2>
       <ion-text class="smaller">{{seriesItem.description}}</ion-text>
    </ion-label>
</ion-item>
Related