我的组件中有一个简单的输入,它使用[(ngModel)]:

<input type="text" [(ngModel)]="test" placeholder="foo" />

当我启动应用程序时,即使没有显示组件,也会出现以下错误。

zone.js:461未处理的Promise拒绝:模板解析错误:无法绑定到“ngModel”,因为它不是“input”的已知属性。

以下是组件。ts:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Intervention } from '../../model/intervention';

@Component({
   selector: 'intervention-details',
   templateUrl: 'app/intervention/details/intervention.details.html',
   styleUrls: ['app/intervention/details/intervention.details.css']
})
    
export class InterventionDetails
{
   @Input() intervention: Intervention;
    
   public test : string = "toto";
}

当前回答

结合所有可能的解决方案:

检查您的键入是否正确。应为“[(ngModel)]”,大写为“M”。检查TS文件中是否有导入FormsModule。如果没有,可以这样做:

在app.module.ts中,添加以下行

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
  ],
  imports: [
    xyz,
    abc,
    FormsModule
  ],
})

其他回答

这是为那些使用普通JavaScript而不是Type Script的人准备的。除了引用页面顶部的表单脚本文件外,如下所示:

<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>

您还应该告诉模块加载器加载ng.forms.FormsModule。进行更改后,NgModule方法的imports属性如下所示:

导入:[ng.platformBrowser.BrowserModule,ng.forms.FormsModule],

有时,即使我们已经导入了BrowserModule、FormsModule和其他相关模块,我们仍然可能会收到相同的错误。

然后我意识到我们需要按顺序导入它们,这在我的案例中是缺失的。因此,顺序应该类似于BrowserModule、FormsModule和ReactiveFormsModul。

根据我的理解,功能模块应该遵循Angular的基本模块。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  declarations: [
    AppComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

简单解决方案:在文件app.module.ts中-

示例1

import {FormsModule} from "@angular/forms";
// Add in imports

imports: [
 BrowserModule,
 FormsModule
 ],

示例2

如果要使用[(ngModel)],则必须在app.module.ts中导入FormsModule:

import { FormsModule  } from "@angular/forms";
@NgModule({
  declarations: [
    AppComponent, videoComponent, tagDirective,
  ],
  imports: [
    BrowserModule,  FormsModule

  ],
  providers: [ApiServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

如果此组件位于根模块(即app.module.ts)中,则需要在根模块中导入FormsModule

请打开app.module.ts

从@angular/forms导入FormsModule

Ex:

import { FormsModule } from '@angular/forms';

and

@NgModule({
imports: [
   FormsModule
],
})

注意:请记住,ngModel指令被定义为Angular FormsModule的一部分,您需要在Angular模块元数据的imports:[…]部分中包含FormsModul,在该部分中使用它。