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

当前回答

可能有以下原因:

你的模块在imports[]中没有CommonModule 你使用*ngFor或*ngIf的组件不是任何模块的一部分。 你可能在*ngFor中有拼写错误,比如**ngFor或*ngFor等。 如果一切正常,重新启动你的应用程序,即ng serve或IDE,即VS Code, IntelliJ等。

其他回答

app.module.ts修复并更改为:在app模块中导入BrowserModule

import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [
    AppComponent    
  ],
  imports: [
    BrowserModule, 
  ],     
  providers: [],
  bootstrap: [AppComponent]
})

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

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

我有一个问题,因为json数据中的空白。

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

我已经在mycomponent.module中导入了CommonModule。和app.module中的BrowserModule。ts,将MyComponent添加到@ngModule的声明中,并重置vscode,就像前面提到的所有解决方案一样。

最终解决了这个问题,我没有通过获取请求迭代接收到的数据,而是使用与ElementModel匹配的硬编码数据模拟elements数组。它工作没有问题。

意识到我的ElementModel接口与我从取回请求接收到的数据不匹配。

希望这能帮助到一些人。