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

当前回答

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

其他回答

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

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

我有同样的错误,但我有CommonModule导入。相反,我在不应该的地方留下了逗号,因为在分割模块时需要复制/粘贴:

@NgModule({
    declarations: [
        ShopComponent,
        ShoppingEditComponent
    ],
    imports: [
        CommonModule,
        FormsModule,
        RouterModule.forChild([
            { path: 'shop', component: ShopComponent }, <--- offensive comma
        ])
    ]
})

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

所以请确保

指令中没有语法错误 浏览器(在应用程序模块)和公共(在其他/子)模块被导入(与上面提到的Günter Zöchbauer相同) 如果你在应用程序中有路由,那么路由模块应该导入到应用程序模块中 所有路由组件的模块也被导入到App模块中,例如: app-routing.module。Ts为: const routes: routes = [ {path: ",组件:CustomerComponent}, {path: 'admin',组件:AdminComponent} ];

然后App模块必须导入@NgModule()中的CustomerComponent和AdminComponent模块。

将该组件添加到app.module中

import { ModalComponent } from './modal/modal.component';

@NgModule({
  declarations: [ModalComponent],
  entryComponents: [ModalComponent],
  
  }),
  providers: [
  ],
  bootstrap: [AppComponent]
})