【问题标题】:Tour of Heroes tutorial -- seems like *ngFor not working英雄之旅教程——似乎 *ngFor 不起作用
【发布时间】:2019-05-02 22:02:26
【问题描述】:

我在教程中已经达到了创建 mock-heroes.ts(HEROES 中的英雄对象数组)的重点;到目前为止一切正常。我在<li> 元素中添加了*ngFor 指令,但应用程序不显示英雄列表。

如果我取出 *ngFor 并放入一个“香草”<li> 元素(例如,<li>New item</li>),我会得到一个列表元素(“新项目”)。如果我在 <ul>...</ul> 元素之后添加 html,就会显示出来。

heroes.component.html:

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

模拟英雄.ts:

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

hero.ts:

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

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})

export class HeroesComponent implements OnInit {
   heroes = HEROES;
  constructor() { }
  ngOnInit() { }
}

我希望看到:

   Tour of Heroes!
     My Heroes
   11 Mr. Nice
   12 Narco
   ...

我得到了前两行,但没有英雄列表。控制台显示没有错误。

目录结构:

src
   app
      files: app.module.ts, app.component.*, hero.ts, mock-heroes.ts
      heroes
         files: heroes.component.*

【问题讨论】:

  • 你能分享你的文件夹结构吗?
  • 检查一下,它在那里工作:stackblitz.com/edit/angular-dwrq38
  • @brunobastosg 感谢您的指点。我的代码似乎与之匹配,但不起作用。我看不出有什么区别(我敢肯定这很简单/愚蠢)。
  • @AustinTFrench heroes 是组件中变量的名称。命名正确。

标签: angular


【解决方案1】:

我不知道发生了什么,但我停下来然后启动了服务器……一切都开始工作了。我猜我有一些错误已修复,但问题很基本,需要重新启动服务器。

感谢您的各种想法!

【讨论】:

  • 如果你改变了 angular.json 你需要“重启”服务器。不知道是不是你的情况
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
相关资源
最近更新 更多