I'm looking into the Tour of Heroes tutorial from Angular2 and I'm stuck with not being able to get the list of heroes that are defined in the array. Although the ngFor seems to be working as it shows 10 listed items(just the list dots) but the content (id and name) are missing.
Here is the code that I have until now:
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 as to where I might have messed it up?
The problem with the second part of your template where hero
object is undefined (because it's not the same hero
as the one in the loop). You can fix it like this:
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With