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

当前回答

我收到了错误,因为我正在使用的组件没有在模块的declarations:[]部分中注册。

添加组件后,错误消失了。我本希望看到比这条错误消息更清晰的信息来指出真正的问题。

其他回答

需要记住的事情:

当使用自定义模块(除AppModule之外的模块)时,需要导入其中的公共模块。

yourmodule.module.ts

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

@NgModule({
  imports: [
    CommonModule
  ],
  exports:[ ],
  declarations: []
})

当ngFor语法没有正确编写时,这个错误也会被抛出,在我的例子中,我有:

<ng-template *ngForOf="let key of SomeObject; index as i">

它通过使用以下语法得到了修复:

<ng-template ngFor let-key [ngForOf]="SomeObject" let-i="index">

我开始在Angular8基础上的live项目得到了上述问题,但当使用“app-routing。我们忘记导入CommonModule了。记得导入!

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

@NgModule({
  imports: [
    CommonModule
]})

它将解决你的错误。

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

feature.routing.module.ts:

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

feature.module.ts:

     imports: [ FeatureRoutingModule ],
     declarations: [],

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

有点晚了,但我最近遇到了这种情况。这个答案没有解决我的问题。

我的前提

我在项目中使用了自定义目录结构。有问题的组件位于components目录中。 我发现类似错误的组件是使用CLI原理图和——skip-import选项创建的 NPX ng g c——skip-import ../components/my-component

解决方案

因为我使用了——skip-import(见注释)选项,我发现我的组件没有添加到模块中的declarations数组中。将组件添加到相同的组件中解决了这个问题。

注意:如果没有这个,你就不能在app目录外创建组件。