I followed step by step the official tutorial to learn Angular2. I allways did exactly what it indicates but I can't get the heroes list through ngFor directive. So, this my code:
app.component.ts
import { Component } from '@angular/core';
export class Hero {
id: number;
name: string;
};
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' }
];
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Tour of Heroes';
hero = HEROES;
};
app.template.ts
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name">
</div>
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes">
<span class="badge">{{hero.id}}</span>
{{hero.name}}
</li>
</ul>
Browser result
Here is the tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt2.html And now? What's wrong with that? Are just the first steps! Thanks for help me.
When you do "let hero of heroes" hero is the variable that is let for you and what you iterate with. But heroes needs to be declared in your component. Is the array you refer to for iteration. It is case sensitive so the true is that you have not declared heroes, you have declared HEROES.
Finally I got it, the error was here:
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name">
</div>
The variable hero.name and hero.id was not declarated until you select a hero of the list. So be carefully with that if you follow the oficial tutorial because they say that it would have to function but is not like this until you complete the code with the selection function.