You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ngFor列表项不显示问题求助

问题分析与解决:Angular组件中*ngFor不渲染列表项

嘿,这个问题其实是个很容易踩的TypeScript语法小坑!你的skins属性根本没有被赋予实际的数组数据,所以*ngFor自然遍历不出任何内容,也就不会生成li元素了。

问题根源

你在定义skins时用了类型注解的语法(冒号:):

skins: [{
  // ... 对象结构
}];

在TypeScript里,这种写法是给skins指定一个元组类型,但并没有给它赋值任何实际的数组。skins此时的默认值是undefined,*ngFor对undefined会直接跳过渲染。

修正方案

把冒号:改成等号=,给skins赋值你定义的数组:

import { Component } from '@angular/core';
@Component({
  selector: 'skin',
  templateUrl: './skin.component.html',
  styleUrls: ['./skin.component.css']
})
export class SkinComponent {
  // 用等号 = 给skins赋值数组
  skins = [{
    id: 1, className: 'color-circle blue light', skinName: 'Blue light'
  }, {
    id: 2, className: 'color-circle orange light', skinName: 'Orange light'
  }, {
    id: 3, className: 'color-circle lime light', skinName: 'Lime light'
  }, {
    id: 4, className: 'color-circle purple light', skinName: 'Purple light'
  }, {
    id: 5, className: 'color-circle teal light', skinName: 'Teal light'
  }];
  constructor() { }
}

进阶优化(推荐)

如果想同时保证类型安全,可以先定义一个Skin接口,再给skins指定类型并赋值:

import { Component } from '@angular/core';

// 定义Skin类型接口
interface Skin {
  id: number;
  className: string;
  skinName: string;
}

@Component({
  selector: 'skin',
  templateUrl: './skin.component.html',
  styleUrls: ['./skin.component.css']
})
export class SkinComponent {
  // 指定类型为Skin数组,并赋值
  skins: Skin[] = [{
    id: 1, className: 'color-circle blue light', skinName: 'Blue light'
  }, {
    id: 2, className: 'color-circle orange light', skinName: 'Orange light'
  }, {
    id: 3, className: 'color-circle lime light', skinName: 'Lime light'
  }, {
    id: 4, className: 'color-circle purple light', skinName: 'Purple light'
  }, {
    id: 5, className: 'color-circle teal light', skinName: 'Teal light'
  }];
  constructor() { }
}

这样修改后,*ngFor就能正常遍历skins数组,渲染出所有的列表项了。

内容的提问来源于stack exchange,提问作者derstauner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:25:09