【问题标题】:ngFor is not workingngFor 不工作
【发布时间】:2018-02-09 13:43:12
【问题描述】:

我正在使用带有 JIT 编译器的 Angular 4.3.3,并在运行我的应用程序时收到以下错误:

Property binding ngforOf not used by any directive on an embedded template. 
Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations".

我已确保在我的主应用程序模块中导入BrowserModule,并在我的子模块中导入了CommonModule,该错误源自于此。

这是引发错误的模板:

<div class="background"></div>
<div class="content normal-page">
    <ons-fab position="top right" ripple>+</ons-fab>
    <ons-list>
        <ons-list-item *ngFor="let item of items; let i = index">
            <div class="center">
                #{{i}} msg: {{item.msg}}
            </div>
        </ons-list-item>
    </ons-list>
</div>

由于我将正确的模块导入到正确的位置,可能导​​致此错误的原因是什么?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    包含您的组件的 NgModule 需要在 imports 中有 CommonModule

    @NgModule({
      ...,
      imports: [CommonModule],
    })
    export class MySharedModule {}
    

    另外binding ngforOf not used 表示您使用*ngfor 而不是*ngFor 大写F

    【讨论】:

    • 你确定你的代码中没有*ngfor 而不是*ngFor(大写F)吗?
    • 我发现了问题,请参阅我的答案。这是一个 webpack 问题。不过感谢您的帮助。
    • 我看到了,这就解释了为什么它都是小写的。
    • 我明白了。抱歉,我好像不小心跳过了那行。
    【解决方案2】:

    我发现了问题,我让 webpack 最小化了我的模板。一旦我关闭了最小化,它就可以正常工作了。

    {
        test: /\.html$/,
        use: [
            {
                loader: 'html-loader',
                options: {
                    minimize: false
                }
            }
        ]
    }
    

    【讨论】:

    • 但是我应该在哪里更新上面的最小化选项告诉我文件名一次。
    【解决方案3】:

    有时当您忘记了let 时可能会发生这种情况:

    <span *ngFor="teacher of teachers">{{teacher}}</span>
    

    它应该是:

    <span *ngFor="let teacher of teachers">{{teacher}}</span>
    

    【讨论】:

    • 这只是我的错字,甚至没有意识到,谢谢!
    【解决方案4】:

    有时在你使用时会发生

    *ngFor="让dataList中的数据">{{data}}

    试试改成

    *ngFor="让dataList的数据">{{data}}

    您需要将“in”替换为“of”。

    【讨论】:

      【解决方案5】:

      添加 app.module.ts :

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-15
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 2017-09-20
        • 2019-04-11
        • 2021-09-23
        • 2019-03-20
        相关资源
        最近更新 更多