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

当前回答

我得到了同样的错误, 你可以通过以下方法之一进行修复:

如果没有嵌套模块 a.在App模块中导入CommonModule b.导入你在App模块中添加*ngFor的组件,在declarations中定义

// file App.modules.ts
@NgModule({
  declarations: [
    LoginComponent // declarations of your component
  ],
  imports: [
    BrowserModule
    DemoMaterialModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
    ApiService, 
    CookieService, 
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ApiInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})

c.如果你使用单独的模块文件进行路由,那么在routing模块中导入CommonModule否则在App模块中导入CommonModule

// file app.routing.modules.ts
import { LoginComponent } from './login/login.component';
import { CommonModule } from "@angular/common";

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [RouterModule,RouterModule.forRoot(routes), CommonModule],
  exports: [RouterModule]
})

如果您有嵌套模块,则执行该特定模块的第一步

在我的案例中,第二种方法解决了我的问题。 希望这对你有所帮助

其他回答

自定义模块需要通用模块

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


@NgModule({
  imports: [
    CommonModule
  ]
})

需要记住的事情:

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

yourmodule.module.ts

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

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

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

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

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

*ngFor="let ingredient of ingredients"

**ngFor="let ingredient of ingredients"

未来的读者

检查以下每一项:

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