After the browser refreshes, the list of heroes doesn't appear

424 Views Asked by At

I've been progressing well on the angular tutorial "tour of heroes" until my list of heroes failed to display while using angular's repetitive directive, *ngFor. Using npm -v6.4.1 and node -v8.12.0. The code is exact to what is in the tutorial.

I created a Hero class in its own file in the src/app folder and gave it id and name properties.

export class Hero {
  id: number;
  name: string;
}

This file called mock-heroes.ts in the src/app/ folder, Defines a HEROES constant as an array of ten heroes and export it.

import { Hero } from './hero';

export const HEROES: Hero[] = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'},
  {id: 16, name: 'RubberMan'},
  {id: 17, name: 'Dynama'},
  {id: 18, name: 'Dr IQ'},
  {id: 19, name: 'Magma'},
  {id: 20, name: 'Tornado'},
];

I opened the HeroesComponent class file and imported the mock HEROES as shown below

import { HEROES } from '../mock-heroes';

In the same file (HeroesComponent class), I defined a component property called heroes to expose HEROES array for binding as shown below.

export class HeroesComponent implements OnInit {

heroes = HEROES;

I listed heroes with *ngFor as shown below in the heroes.component.html file by modifying the

  • tag.

    <h2>My Heroes</h2>
    <ul class = "heroes">
      <li *ngFor="let hero of heros">
        <span class = "badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    

    Here is the link to the tutorial on the angular page.https://angular.io/tutorial/toh-pt2. Remember, the list doesn't display in the browser and i don't get any errors in the console. I'm using npm -v6.4.1 and node -v8.12.0

  • 2

    There are 2 best solutions below

    0
    Ikhlak S. On

    You have a variable typo heros in your loop statement.

    It should be heroes instead:

    <h2>My Heroes</h2>
    <ul class = "heroes">
      <li *ngFor="let hero of heroes">
        <span class = "badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    
    0
    Dhanika On

    In your .ts

    heros = HEROES;
    

    In your .html

    <h2>My Heroes</h2>
    <ul class = "heroes">
      <li *ngFor="let hero of heros">
        <span class = "badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>