我的组件中有一个简单的输入,它使用[(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(例如,从共享模块),如果导入的组件未在声明中声明,也会发生此错误:

我参加了Deborah Kurata的Angular Routing课程。当我在Angular Route的组件属性上添加导入的组件ProductEditInfoComponent时,我忘记在声明属性上添加ProductEditInfoComponent。

在声明属性上添加ProductEditInfoComponent将解决NG8002:无法绑定到“ngModel”,因为它不是“input”的已知属性。问题:

其他回答

确保采用模板驱动的表单方法(https://angular.io/guide/forms),正如@Nikita Sychou已经提到的,您已经用“name”属性修饰了输入字段,例如

<form>
   <input [(ngModel)]="form.email" name="email"></input>

并且FormsModule已导入关联的@NgModule中。这两者都是避免“无法绑定到ngModel”错误的前提条件。如果IDE中仍然存在样式错误,例如IntelliJ抱怨ngModel指令,请忽略它们。。你很好去:-)

简单解决方案:在文件app.module.ts中-

示例1

import {FormsModule} from "@angular/forms";
// Add in imports

imports: [
 BrowserModule,
 FormsModule
 ],

示例2

如果要使用[(ngModel)],则必须在app.module.ts中导入FormsModule:

import { FormsModule  } from "@angular/forms";
@NgModule({
  declarations: [
    AppComponent, videoComponent, tagDirective,
  ],
  imports: [
    BrowserModule,  FormsModule

  ],
  providers: [ApiServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

检查您的键入是否正确。应为“[(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     <-------
  ],
  [...]
})

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