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

其他回答

当您试图对“input”元素使用“ngModel”指令时,Angular中出现了一个著名的错误,但“ngModel”指令不被识别为“input“元素的属性。解决方案是在应用程序中导入“FormsModule”,并将其包含在模块的“imports”数组中。这样地:

import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
// other imports
],
// other properties
})
export class AppModule { }

对我来说,问题是,我忘记在模块的声明数组中声明组件。

@NgModule({
 declarations: [yourcomponentName]
})

从“@angular/forms”导入{FormsModule};@Ng模块({进口:[表单模块],})

确保[(ngModel)]实际拼写为“ngModel”,大写为M。我花了几分钟没看到这个

对于我的场景,我必须将[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 { }