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

当前回答

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

请打开app.module.ts

从@angular/forms导入FormsModule

Ex:

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

and

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

其他回答

在您愿意使用ngModel的模块中,必须导入FormsModule

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

@NgModule({
  imports: [
    FormsModule,
  ],

})
export class AbcModule { }

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

@NgModule({
 declarations: [yourcomponentName]
})

在应用程序模块中导入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 { }

当我第一次做这个教程时,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);

注意:请记住,ngModel指令被定义为Angular FormsModule的一部分,您需要在Angular模块元数据的imports:[…]部分中包含FormsModul,在该部分中使用它。