0

在使用 Angular 的重复指令 *ngFor 时,我的 Angular 教程“英雄之旅”一直进展顺利,直到我的英雄列表无法显示。使用 npm -v6.4.1 和节点 -v8.12.0。代码与教程中的代码完全相同。

我在 src/app 文件夹中自己的文件中创建了一个 Hero 类,并为其提供了 id 和 name 属性。

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

在 src/app/ 文件夹中这个名为 mock-heroes.ts 的文件,定义一个 HEROES 常量为一个由十个英雄组成的数组并导出它。

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'},
];

我打开 HeroesComponent 类文件并导入模拟 HEROES 如下图

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

在同一个文件(HeroesComponent 类)中,我定义了一个名为 heros 的组件属性来公开 HEROES 数组以进行绑定,如下所示。

export class HeroesComponent implements OnInit {

heroes = HEROES;

我在 heros.component.html 文件中通过修改 *ngFor 列出了如下所示的英雄

  • 标签。

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

    这是角度页面上教程的链接。https://angular.io/tutorial/toh-pt2。请记住,该列表不会显示在浏览器中,并且我在控制台中没有收到任何错误。我正在使用 npm -v6.4.1 和 node -v8.12.0

  • 4

    2 回答 2

    0

    您的循环语句中有一个变量错字heros

    它应该是heroes

    <h2>My Heroes</h2>
    <ul class = "heroes">
      <li *ngFor="let hero of heroes">
        <span class = "badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    
    于 2018-10-08T09:39:48.487 回答
    0

    在你的 .ts

    heros = HEROES;
    

    在你的 .html

    <h2>My Heroes</h2>
    <ul class = "heroes">
      <li *ngFor="let hero of heros">
        <span class = "badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    
    于 2018-10-12T11:52:29.677 回答