我的组件中有一个简单的输入,它使用[(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 2的,但我是Angular 4的,这些答案都没有帮助。

在Angular 4中,语法需要

[(ngModel)]

其他回答

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

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

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

在要使用[(ngModel)]的模块中导入FormsModule

您需要导入FormsModule。

打开app.module.ts并添加行

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

and

@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

实际上,在大多数情况下,FormsModule已经导入。所以你要做的是确保

组件已正确添加到app.module.ts文件的声明数组中。您应该验证绑定是否拼写正确。正确拼写为[(ngModel)]