ng对于未找到指令

问题描述 投票:0回答:9

我正在使用 Angular 4.3.3 和 JIT 编译器,当我运行我的应用程序时,出现以下错误:

属性绑定

ngforOf
嵌入模板上的任何指令均不使用。 确保属性名称拼写正确,并且所有指令都列在
@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
9个回答
27
投票

包含您组件的 NgModule 需要在

CommonModule
 中包含 
imports

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

此外

binding ngforOf not used
表示您正在使用
*ngfor
而不是大写的
*ngFor
F


20
投票

有时,当您忘记了 for 中的

let
时,可能会发生这种情况:

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

应该是:

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

11
投票

有时使用时可能会发生

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

尝试将其更改为

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

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


5
投票

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

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

3
投票

如果您在 Angular 14 或 15 中使用独立组件,您可以将 CommonModule 导入到组件中或解构并获取 NgForOf:

import {Component} from '@angular/core'
import {Link} from "./link";
import {Container} from "./container";
import {menu} from "../../db/db";
import {NgFor, NgForOf} from "@angular/common";
@Component({
  selector: 'navigation',
  template: `
    <nav class="bg-white border-b border-gray-100">
      <container>
       <ul class="flex space-x-5">
            <li *ngFor="let link of menu">
            <nav-link href="">{{link.name}}</nav-link>
            </li>
        </ul>
      </container>
    </nav>
  `,
  standalone: true,
  imports: [
      Link, 
      Container, 
      NgForOf
      ],
   }) export class Navigation { 
      menu = menu;
   }

0
投票

添加app.module.ts:

import { CommonModule } from '@angular/common';

@NgModule({
    imports: [
        CommonModule,
    ],


})
export class AppModule { }

0
投票

您还需要确保您正在处理的组件已在您的

module.ts
文件中声明。

例如在您使用

*ngFor:

的组件中
@Component({
  ...
  template: '<div *ngFor="let thing of things">..</div>'
})
export class MyComponent {...

此组件也必须在您的

module.ts file
:

中声明
@NgModule({
  ...
  declarations: [
    MyComponent
  ]

我使用 VS Code 扩展为我创建组件,但没有在应用程序模块中注册它们,而且我经常忘记手动执行此操作,从而导致此问题。


0
投票

在 Ionic 6 中,在我的主页中我需要添加 CommonModule:

import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-home',
...
  imports: [CommonModule]
})
export class HomePage implements OnInit {

我正在使用空白模板。如果您使用带有模块的页面,则需要在页面模块中添加 CommonModule。


0
投票

我的问题是我写了“as”而不是“of”

let o of options

基本上,任何语法错误(例如缺少 let、未将 ngFor 大写或写为“as”)都可能导致此问题。

© www.soinside.com 2019 - 2024. All rights reserved.