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

当前回答

如果您有模块实现,则必须导入组件并在声明中设置组件

祝你编程好运:)

其他回答

如果您没有在特性模块中声明路由组件,也会发生这种情况。例如:

feature.routing.module.ts:

...
    {
        path: '',
        component: ViewComponent,
    }
...

feature.module.ts:

     imports: [ FeatureRoutingModule ],
     declarations: [],

注意ViewComponent不在declarations数组中,而它应该在。

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

为了防止有人在尝试导入CommonModule后仍然遇到错误,请尝试重新启动服务器。它竟然有效

自定义模块需要通用模块

import { CommonModule } from "@angular/common";


@NgModule({
  imports: [
    CommonModule
  ]
})

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

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