我使用的是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>

当前回答

你必须在使用ngFor、ngIf等内置指令的模块中导入CommonModule。

import { CommonModule } from '@angular/common'
       
@NgModule({
    imports: [
        CommonModule
    ]
})
    
export class ProductModule { }

其他回答

以我为例,问题是我的队友在模板中提到了*ngfor而不是*ngfor。奇怪的是,没有正确的错误来处理这个问题(在Angular 4中)。

在我的例子中,问题是,我在*ngFor中使用了const而不是let。

你必须在使用ngFor、ngIf等内置指令的模块中导入CommonModule。

import { CommonModule } from '@angular/common'
       
@NgModule({
    imports: [
        CommonModule
    ]
})
    
export class ProductModule { }

我遇到过类似的错误(*ngIf),即使我所有的导入都是OK的,并且组件呈现时没有任何其他错误+路由是OK的。

在我的例子中,AppModule没有包含这个特定的模块。奇怪的是,它并没有抱怨这一点,但这可能与Ivy使用ng serve的方式有关(类似于根据路由加载模块,但不考虑它的依赖关系)。

我已经在mycomponent.module中导入了CommonModule。和app.module中的BrowserModule。ts,将MyComponent添加到@ngModule的声明中,并重置vscode,就像前面提到的所有解决方案一样。

最终解决了这个问题,我没有通过获取请求迭代接收到的数据,而是使用与ElementModel匹配的硬编码数据模拟elements数组。它工作没有问题。

意识到我的ElementModel接口与我从取回请求接收到的数据不匹配。

希望这能帮助到一些人。