我使用的是Angular2 2.1.0。当我想要显示公司列表时,我得到了这个错误。

在file.component.ts中:

public companies: any[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

在file.component.html中:

<tbody>
  <tr *ngFor="let item of companies; let i =index">
     <td>{{i}}</td>
     <td>{{item.name}}</td>
  </tr>
</tbody>

当前回答

可能有以下原因:

你的模块在imports[]中没有CommonModule 你使用*ngFor或*ngIf的组件不是任何模块的一部分。 你可能在*ngFor中有拼写错误,比如**ngFor或*ngFor等。 如果一切正常,重新启动你的应用程序,即ng serve或IDE,即VS Code, IntelliJ等。

其他回答

我有一个问题,因为**代替*

*ngFor="let ingredient of ingredients"

**ngFor="let ingredient of ingredients"

通过在其他(新/自定义)模块中导入CommonModule,许多答案似乎趋于一致。 这一步在所有情况下都是不够的。

完整的解决方案分为两步:

让NgIf, NgFor等指令对你的项目可见。 在主组件中以正确的方式重新组装所有内容

点1 主模块中的BrowserModule似乎足够访问NgFor了。 Angular文档把它写在这里:。

CommonModule用于导出所有基本的Angular指令和管道,比如NgIf、NgForOf、DecimalPipe等等。由BrowserModule重新导出,

参见此处接受的答案:CommonModule vs BrowserModule

点2 唯一需要改变的是(在我的情况下)如下:

导入模块 导入组件 Ng构建(重要!) ng服务

app.module.ts

@NgModule({
    imports: [
        BrowserModule,
        OtherModule
    ],
    declarations: [OtherComponent, AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {
}

other.html

<div *ngFor='let o of others;'> 
</div>

other.component.ts

@Component({
    selector: 'other-component',
    templateUrl: './other.html'
})
export class OtherComponent {
}

app.module.ts

@NgModule({
    imports: [],
    providers: []
})
export class OtherModule{
}

在所有代码中使用正确的语法后,请查看是否在angular模块的声明中提到了你的组件。 如下所示:

@NgModule ({ 声明:[ AppComponent, YourComponent ),

未来的读者

检查以下每一项:

该组件是在SINGLE angular模块中声明的 确保你有import {CommonModule} from '@angular/common'; 重新启动IDE/编辑器 重新启动开发服务器(ng serve)

将BrowserModule添加到@NgModule()中的imports:[],如果它是根模块(AppModule),否则是CommonModule。

// older Angular versions
// import {BrowserModule, CommonModule} from '@angular/common';

import { BrowserModule } from '@angular/platform-browser'
..
..
@NgModule({
  imports: [BrowserModule, /* or CommonModule */],
  ..
})