user6579134
user6579134

Reputation: 839

display multiple nested data with angular6

I'm receiving JSON data from an API which has some child objects as well. The API has a menu level and down the menu, it's having meals. What I want to do is to display meals relating to each menu under the menu

JSON from API

[{"id":6,"name":"Menu 1","serveDate":"2019-05-10","meals":[{"id":13,"name":"Rice with Stew","description":"rice","image":"","mealType":"BREAKFAST","unitPrice":5,"status":"ENABLED"}]},{"id":5,"name":"Menu 2","serveDate":"2019-06-10","meals":[{"id":13,"name":"Corn Flakes,"description":"Flakes","image":"","mealType":"BREAKFAST","unitPrice":5,"status":"ENABLED"}]},{"id":4,"name":"Menu 3","serveDate":"2019-07-10","meals":[]}]

HTML

<div *ngFor="let item of menuList">
    <h2>Menu</h2>
    {{item.name}} - {{item.servate}}
    <h2 *ngFor="let item of menuList.meals">Meals</h2>
    {{item.name}} - {{item.mealType}}
  </div>

JS

getMenus() {
  this.menuServices.menuList(this.pagedData)
  .subscribe(
    response => {
      if (response && response.code === HttpStatus.OK) {
        this.menuList = response.data;
      }
    },

  );
}

Any help on how to make this work correctly the way it should work?

Upvotes: 1

Views: 323

Answers (3)

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

No need to access the main list as you have your meals array in the item object.

Change HTML Code to:

<div *ngFor="let item of menuList">
    <h2>Menu</h2>
    {{item.name}} - {{item.servate}}
  <h2>Meals</h2>
    <div *ngFor="let item of item.meals">
        {{item.name}} - {{item.mealType}}
    </div>
</div>

Upvotes: 1

Alexander Gasnikov
Alexander Gasnikov

Reputation: 41

When you're doing something like let item of menuList that means the item variable should be used to refer to an individual item within your loop. To avoid confusion, I'd also recommend naming these item vars for nested loops differently. Another important thing to keep in mind that all the markup that you want to be output for each array item should be wrapped with an element with *ngFor. It's not the case with your <h2> tag being printed for each meal, but not the meal description.

Edit the template as follows:

<div *ngFor="let menuItem of menuList">
   <h1>Menu</h1>
   <h2>{{menuItem.name}} - {{menuItem.serveDate}}</h2> 
   <p>maybe description here</p>
   <h3>Meals</h2>
   <p *ngFor="let mealItem of menuItem.meals">{{mealItem.name}} - {{mealItem.mealType}}</p>
</div>

Upvotes: 1

Aarsh
Aarsh

Reputation: 2595

<div *ngFor="let menu of menuList">
    <h2>Menu</h2>
    {{menu.name}} - {{menu.servate}}
  <h2>Meals</h2>
    <ng-container *ngFor="let meal of menu.meals">
        {{meal.name}} - {{meal.mealType}}
    </ng-container>
</div>

Using this way you don't have to add unnecessary divs or any other html tag for looping in angular.

this is the perfect way to do nested loops without changing your html

Upvotes: 4

Related Questions