Angular2:无法从英雄之旅教程中的数组中检索列表

时间:2016-02-10 19:11:52

标签: typescript angular

我正在研究Angular2中的“英雄之旅”教程,但我无法获得数组中定义的英雄列表。虽然ngFor似乎正在工作,因为它显示了10个列出的项目(只是列表点),但缺少内容(id和名称)。

这是我到目前为止的代码:

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" }
];

有关我可能搞砸了哪里的任何建议?

1 个答案:

答案 0 :(得分:5)

模板的第二部分中hero对象未定义的问题(因为它与循环中的hero不同)。你可以像这样解决它:

@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;
}

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