我的组件中有一个简单的输入,它使用[(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将其作为@NgModule decorator中的导入值传递

基本上,app.module.ts文件应该如下所示:

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule }   from '@angular/forms';
    import { AppComponent }  from './app.component';
    import {AppChildComponent} from './appchild.component';
    @NgModule({
      imports:      [ BrowserModule,FormsModule ],
      declarations: [ AppComponent, AppChildComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

其他回答

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

在Angular 4中,语法需要

[(ngModel)]

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

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

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

当我第一次做这个教程时,main.ts看起来与现在略有不同。它看起来非常相似,但请注意其中的差异(上面的一个是正确的)。

对的:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

旧教程代码:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);

我在运行Angular测试时遇到了同样的错误,因为规范文件中没有添加FormsModule。

我们需要将其添加到所有规范文件中,而为了使应用程序成功运行,我们将在app.module.ts文件中的一个位置添加它。