我使用的是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: []
})

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

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

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

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