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

当前回答

这是为那些使用普通JavaScript而不是Type Script的人准备的。除了引用页面顶部的表单脚本文件外,如下所示:

<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>

您还应该告诉模块加载器加载ng.forms.FormsModule。进行更改后,NgModule方法的imports属性如下所示:

导入:[ng.platformBrowser.BrowserModule,ng.forms.FormsModule],

其他回答

我知道这个问题是关于Angular 2的,但我是Angular 4的,这些答案都没有帮助。

在Angular 4中,语法需要

[(ngModel)]

ngModel来自FormsModule。在某些情况下,您可能会收到此类错误:

您没有将FormsModule导入到声明组件的模块导入数组中,即使用ngModel的组件。您已经将FormsModule导入一个模块,该模块继承了另一个模块。在这种情况下,您有两个选项:

让FormsModule从两个模块(module1和module2)导入导入数组。通常:导入模块不会提供对其导入模块的访问权限。(导入不继承)将FormsModule声明到module1中的导入和导出数组中,以便能够在model2中看到它

(在某些版本中,我遇到了这个问题)您正确导入了FormsModule,但问题出在输入HTML标记上。必须为输入添加name标记属性,[(ngModel)]中的对象绑定名称必须与name属性中的名称相同

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

请打开app.module.ts

从@angular/forms导入FormsModule

Ex:

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

and

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

我面临同样的问题,原因是我在MenuComponent中使用ngModel。我在app.module.ts中导入了MenuComponent,但忘记声明它。

声明MenuComponent解决了我的问题。如下图所示:

在应用程序模块中导入FormsModule。

这将使您的应用程序运行良好。

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {ContactListCopmponent} from './contacts/contact-list.component';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,ContactListCopmponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }