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

当前回答

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

feature.routing.module.ts:

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

feature.module.ts:

     imports: [ FeatureRoutingModule ],
     declarations: [],

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

其他回答

所以请确保

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

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

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

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

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

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

我认为我的情况是一个罕见的情况,但我还是会回答。

我没有任何语法错误,我导入了BrowserModule,我重新声明了我的IDE (VS Code),但我仍然在我的模板中有红线,因为我使用了*ngFor。

这是因为我正在使用一个扩展,Angular语言服务,但它相当老了。更新后,错误停止出现。

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

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

对我来说,问题是我没有在我的app.module.ts中导入定制的模块HouseModule。我有其他的进口。

文件:app.module.ts

import { HouseModule } from './Modules/house/house.module';

@NgModule({
  imports: [
    HouseModule
  ]
})