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

当前回答

只是在修改了几个组件后出现了同样的问题。没有语法错误,所有模块都导入了,但是重新启动服务器解决了这个问题。 错误发生在一个组件中,该组件是在几十次成功提交之前添加的。

以防别人遇到同样的问题。

其他回答

当使用"app-routing. "我们忘记导入CommonModule了。记得导入!

import { CommonModule } from "@angular/common";
@NgModule({  imports: [ CommonModule]})

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

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

如果没有嵌套模块 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]
})

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

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

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

feature.routing.module.ts:

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

feature.module.ts:

     imports: [ FeatureRoutingModule ],
     declarations: [],

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

将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 */],
  ..
})