1

Learning how to display nested data using Angular 2. There are lots of similar questions on the web but I haven't seen anything broken down into a simple object I can follow and repeat.

I have a list that shows a JSON list of heroes: Basic List & Detail for Superman and Batman

My current goal is to show a list of accounts of the selected hero.

My problem is code here related to a list where I'd like to show accounts based on the hero chosen.

My JSON is broken where I can see sub-nested detail but I can't seem to get that level of detail into a list.

hero-detail.component.html

<main class="col-sm-9">
    <div *ngIf="hero">
        <h2>{{hero.user[0].firstName}} {{ hero.user[0].lastName }}</h2>
        <div>
            <label>First Name: </label>
            <input [(ngModel)]="hero.user[0].firstName" placeholder="First Name">
        </div>
        <div>
            <label>Last Name: </label>
            <input [(ngModel)]="hero.user[0].lastName" placeholder="Last Name">
        </div>

        <ul class="list-group">
            <li class="list-group-item" *ngFor="let hero of heroes">
                <div *ngFor="let account of accounts">
                    {{ account[0].accountName }}
                </div>
            </li>
        </ul>
    </div>
</main>

hero-detail.component.ts

import { Component, Input } from '@angular/core';
import { Hero } from './hero';

@Component({
    selector: 'my-hero-detail',
    templateUrl: './heroes-detail.component.html'
})
export class HeroesDetailComponent {

    @Input()
    hero: Hero;

}

hero-component.html

<aside class="col-sm-3">
<div class="list-group">
    <button class="list-group-item" 
        *ngFor="let hero of heroes" 
        [class.selected]="hero === selectedHero" 
        (click)="onSelect(hero)">
        {{ hero.user[0].firstName }} {{ hero.user[0].lastName }}
    </button>
</div>
</aside>

<my-hero-detail [hero]="selectedHero"></my-hero-detail>

heroes.component.ts

import { Component, OnInit }    from '@angular/core';

import { Hero }             from './hero';
import { HeroService }      from './hero.service';

@Component({
    selector: 'app-heroes',
    templateUrl: './heroes.component.html',
    providers: [ HeroService ]
})
export class HeroesComponent implements OnInit {
    title = 'Tour of Heroes';

    heroes: Hero[];
    selectedHero: Hero;

    constructor(
        private heroService: HeroService) { }

    getHeroes(): void {
        this.heroService
            .getHeroes()
            .then(heroes => this.heroes = heroes);
    }

    ngOnInit(): void {
        this.getHeroes();
    }

    onSelect(hero: Hero): void {
        this.selectedHero = hero;
    }

}

mock-heroes.ts

import { Hero } from './hero';

export const HEROES: Hero[] = 
[
    {
        "heroId": 1001,
        "alias": "Superman",
        "user": [
            {
                "firstName": "Clark",
                "lastName": "Kent",
                "email": "clark.kent@dailyplanet.com"
            }
        ],
        "accounts": [
            {
                accountNum: "1234567890",
                accountName: "Personal Checking",
                type: "checking",
                balance: 1500.00
            },
            {
                accountNum: "2345678901",
                accountName: "Personal Savings",
                type: "savings",
                balance: 2000.00
            }
        ]
    },
    {
        "heroId": 1002,
        "alias": "Batman",
        "user": [
            {
                "firstName": "Bruce",
                "lastName": "Wayne",
                "email": "bruce.wayne@wayne.com"
            }
        ],
        "accounts": [
            {
                accountNum: "1234567890",
                accountName: "Personal Checking",
                type: "checking",
                balance: 7500000.00
            },
            {
                accountNum: "2345678901",
                accountName: "Personal Savings",
                type: "savings",
                balance: 20000000.00
            }
        ]
    }
]

2 Answers2

0

You have to do like this:

<ul class="list-group">
   <li class="list-group-item" *ngFor="let hero of heroes">
       <div *ngFor="let account of hero.accounts">
          {{ account[0].accountName }}
       </div>
   </li>
</ul>

You have to use second *ngFor with hero.accounts, and make your template structure better, you are using hero in top div element, how you are getting that:

<div *ngIf="hero">

So check out first based on your requirement. Hope this help you.

Avnesh Shakya
  • 3,828
  • 2
  • 23
  • 31
  • Thanks for the response Avnesh. This didn't work for me and i didn't see any error. – Phil Jefferies Dec 11 '16 at 19:23
  • Remove `*ngIf="hero"` from the top, you don't have any variable `hero` variable in you component, and use `*ngFor` on top element for treverse all. Not able to understand your structure. – Avnesh Shakya Dec 11 '16 at 19:29
  • Just added the code that adds the ngIf based on the initial page. Hope that helps. – Phil Jefferies Dec 11 '16 at 19:32
  • Try to put out your `
      ....
    ` list outside of `
    ...
    ` container and see if it works.
    – Avnesh Shakya Dec 11 '16 at 19:36
  • I brought the
      outside of the div with the *ngIf="hero" as I saw where your thinking was, but that didn't change anything for me. I'm not getting an command-line errors nor any console errors. The Inspector code, however, shows "template bindings={"ng-reflect-ng-for-of": null }"
    – Phil Jefferies Dec 11 '16 at 19:47
0

This issue was solved using the Elvis operator (?.) from here: Angular2 ngFor Iterating over JSON

hero.ts

export class Hero {
    id: number;
    name: string;
    firstName: string;
    lastName: string;
    accounts: Array<Account>;
}

export interface Account {
    bank: string;
    type: string;
    balance: number;
}

heroes-detail.component.html

<main class="col-sm-9">
    <div *ngIf="hero">
        <h2>{{hero.firstName}} {{ hero.lastName }}</h2>
        <div>
            <label>id: </label>{{hero.id}}
        </div>
        <div>
            <label>First Name: </label>
            <input [(ngModel)]="hero.firstName" placeholder="First Name">
        </div>
        <div>
            <label>Last Name: </label>
            <input [(ngModel)]="hero.lastName" placeholder="Last Name">
        </div>

        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Bank Name</th>
                    <th>Account Type</th>
                    <th>Balance</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let account of hero?.accounts">
                    <td>{{ account.bank }}</td>
                    <td>{{ account.type }}</td>
                    <td>{{ account.balance }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</main>

mock-heroes.ts

import { Hero } from './hero';

export const HEROES: Hero[] = 
[
    {
        "id": 11, 
        "name": "Superman",
        "firstName": "Clark",
        "lastName": "Kent",
        "accounts": [
            {
                "bank": "Chase",
                "type": "Checking",
                "balance": 1000.00
            },
            {
                "bank": "Chase",
                "type": "Savings",
                "balance": 2000.00
            }
        ]
    },
    {
        "id": 12, 
        "name": "Batman",
        "firstName": "Bruce",
        "lastName": "Wayne",
        "accounts": [
            {
                "bank": "Bank of Gotham",
                "type": "Checking",
                "balance": 1000000000.00
            },
            {
                "bank": "Bank of Gotham",
                "type": "Savings",
                "balance": 2000000000.00
            }
        ]
    },
    {
        "id": 13, 
        "name": "Wonder Woman",
        "firstName": "Diana",
        "lastName": "Prince",
        "accounts": [
            {
                "bank": "",
                "type": "",
                "balance": 0.00
            },
            {
                "bank": "",
                "type": "",
                "balance": 0.00
            }
        ]
    }
]
Community
  • 1
  • 1