Angular使用*ngFor报NG0303错误,导入CommonModule无效求助
解决Angular NG0303: Can't bind to 'ngForOf' 错误
以下是针对你问题的排查和解决步骤:
确认组件所在模块的CommonModule导入
如果你是把_GamesComponent放在了特性模块(比如GamesModule)中,根模块(app.module.ts)的CommonModule/BrowserModule导入不会自动作用于特性模块。必须在该特性模块的imports数组中单独导入CommonModule:// games.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { _GamesComponent } from './games.component'; @NgModule({ declarations: [_GamesComponent], imports: [CommonModule] // 必须在这里导入 }) export class GamesModule { }检查组件声明是否正确
确保_GamesComponent已经被正确添加到对应模块的declarations数组中,且没有在多个模块中重复声明(Angular不允许组件跨模块重复声明)。验证组件类的数据源
确认组件类中的AllGame是公共可访问的属性,并且已经被正确初始化(比如赋值为数组):// games.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-games', templateUrl: './games.component.html' }) export class _GamesComponent { public AllGame: any[] = []; // 确保是公共属性且已初始化 // 或在ngOnInit中赋值数据 ngOnInit() { // 示例:模拟获取游戏数据 this.AllGame = [/* 你的游戏数据 */]; } }独立组件的特殊处理
如果_GamesComponent是独立组件(组件装饰器中设置了standalone: true),需要直接在组件的imports数组中导入CommonModule,不需要依赖模块导入:// games.component.ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; // 导入CommonModule @Component({ selector: 'app-games', templateUrl: './games.component.html', standalone: true, imports: [CommonModule] // 独立组件需在这里导入 }) export class _GamesComponent { public AllGame: any[] = []; }
内容的提问来源于stack exchange,提问作者user25080199
相关产品推荐
相关产品推荐

