我的组件中有一个简单的输入,它使用[(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";
}

当前回答

我在运行Angular测试时遇到了同样的错误,因为规范文件中没有添加FormsModule。

我们需要将其添加到所有规范文件中,而为了使应用程序成功运行,我们将在app.module.ts文件中的一个位置添加它。

其他回答

ngModel应该从@angular/forms导入,因为它是FormsModule的一部分。所以我建议您更改app.module.ts,如下所示:

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

[...]

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

您需要导入FormsModule。

#Open app.module.ts
#add the lines

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

@NgModule({
    imports: [
       FormsModule   <--------add this 
    ],
})


if you are using reactive form then also added  ReactiveFormsModule

您需要在app.module.ts中导入FormsModule并添加行

 import { FormsModule } from '@angular/forms';
    @NgModule({
      imports: [
       
        FormsModule
      ]
    })

FormsModule中声明的ngModel指令允许您将模板驱动表单中的控件绑定到数据模型中的财产。当包含使用双向数据绑定语法[(ngModel)]的指令时,Angular可以跟踪控件的值和用户交互,并保持视图与模型同步。

在要使用[(ngModel)]的模块中导入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],