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

我必须导入ReactiveFormsModule,因为我正在使用FormBuilder类创建一个反应式表单。

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

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

其他回答

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

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

@NgModule({
 declarations: [yourcomponentName]
})

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

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

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

即使在功能模块中直接或间接导入FormsModule(例如,从共享模块),如果导入的组件未在声明中声明,也会发生此错误:

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

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

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

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

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

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