*ngFor无内容显示求助:Angular英雄列表渲染问题排查
问题排查与解决方案
嘿,这问题其实一眼就能看穿——你在组件类和模板里的变量名不匹配啦!
问题根源
在heroes.component.ts里,你把英雄数组赋值给了变量hero:
hero = HEROES;
但在对应的模板heroes.component.html中,*ngFor循环遍历的却是heroes:
<li *ngFor="let hero of heroes">
Angular找不到名为heroes的组件属性,自然没办法渲染出任何内容。
修复方案
只需要把组件类里的变量名改成heroes(复数形式更符合数组的语义),让它和模板里的变量名保持一致就行:
修改后的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 { // 将变量名从hero改为heroes heroes = HEROES; selectedHero: Hero; constructor() { } ngOnInit() { } }
保存修改后重新运行项目,你的英雄列表应该就能正常显示了!
额外排查小提示(后续遇到类似问题时可用)
- 打开浏览器控制台查看报错信息,Angular通常会在属性不存在时抛出明确的提示
- 确保组件类中的属性是公共的(TypeScript中默认就是public,所以本次问题不涉及这点)
- 确认组件已经在对应的NgModule中完成声明
内容的提问来源于stack exchange,提问作者Tsiresgrammeur
相关产品推荐
相关产品推荐

