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

当前回答

您需要导入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

其他回答

为了能够对表单输入使用双向数据绑定,您需要在Angular模块中导入FormsModule包。

有关更多信息,请参阅此处的Angular 2官方教程和表单的官方文档。

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

请打开app.module.ts

从@angular/forms导入FormsModule

Ex:

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

and

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

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

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

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

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

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

在Angular中使用双向绑定之前,需要将FormsModule包导入到模块中。

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

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

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

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

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

[...]

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