我的组件中有一个简单的输入,它使用[(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包导入到模块中。

通过将FormsModule添加到模块内的imports数组(例如app.module.ts),可以这样做。

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

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

其他回答

对于我的场景,我必须将[CommonModule]和[FormsModule]导入到我的模块

import { NgModule } from '@angular/core' 
import { CommonModule } from '@angular/common'; 
import { FormsModule } from '@angular/forms'; 

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }

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

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

这是为那些使用普通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],

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

最近,我发现错误不仅发生在您忘记在模块中导入FormsModule的情况下。在我的案例中,问题出现在以下代码中:

<input type="text" class="form-control" id="firstName"
                   formControlName="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

我通过更改表单ControlName->name来修复它

<input type="text" class="form-control" id="firstName"
                   name="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">