Angular2: cannot get list from array in Tour of Heroes tutorial

I am studying the Tour of Heroes tutorial from Angular2 and I am stuck not being able to get a list of heroes that are defined in an array. Although ngFor works, since it shows 10 listed items (only list points), but the contents (id and name) are missing.

Here is the code that I still have:

import {Component} from 'angular2/core'; interface Hero { id: number; name: string; } @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <h2>My Heroes</h2> <ul> <li *ngFor="#hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div><label>id: </label> {{hero.id}}</div> <div> <label>name: </label> <input [(ngModel)]="hero.name" placeholder="name"/> </div> ` }) export class AppComponent { public title = 'Tour of Heroes'; public heroes = HEROES; public selectedHero: Hero; } var HEROES: Hero[] = [ { "id": 11, "name": "Arrow" }, { "id": 12, "name": "Flash" }, { "id": 13, "name": "Chuck Norris" }, { "id": 14, "name": "Hulk" }, { "id": 15, "name": "Superman" }, { "id": 16, "name": "Captain Canada" }, { "id": 17, "name": "Iron Man" }, { "id": 18, "name": "Ant Man" }, { "id": 19, "name": "Silver Surfer" }, { "id": 20, "name": "Batman" } ]; 

Any suggestions on where I could have messed it up?

+5
source share
1 answer

The problem with the second part of your template is where the hero object is undefined (because it is not the same hero as the one that is in the loop). You can fix it as follows:

 @Component({ selector: 'my-app', providers: [], template: ` <ul> <li *ngFor="#hero of heroes" (click)="selectedHero = hero"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <div><label>id:</label> {{selectedHero.id}}</div> <div> <label>name: </label> <input [(ngModel)]="selectedHero.name" placeholder="name"/> </div> </div> `, directives: [] }) export class App { public heroes = HEROES; public selectedHero: Hero; } 

Demo: http://plnkr.co/edit/4xivhl1wYTSsiof8QJu4?p=preview

+5
source

Source: https://habr.com/ru/post/1242727/


All Articles