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

其他回答

假设您已经创建了一个新的NgModule,比如说AuthModule专门用于处理您的身份验证需求,请确保也在该AuthModule中导入FormsModule。

如果您将仅在AuthModule中使用FormsModule,则无需在默认AppModule中导入FormModule。

因此,AuthModule中的内容如下:

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

import { authRouting } from './auth.routing';
import { LoginComponent, SignupComponent } from './auth.component';

@NgModule({
  imports:      [
    authRouting,
    FormsModule
   ],
  declarations: [
    SignupComponent,
    LoginComponent
  ]
})
export class AuthModule { }

然后,如果您在其他任何地方都不使用FormsModule,请忘记在AppModule中导入。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

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

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

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

我使用的是Angular 9,我有一个带有[formGroup]属性的'<form'标记。我还有一个指定按钮的“<input”标记,这导致了[(ngModel)]部分的错误。

我只删除了那个(ngModel)部分就解决了这个错误。

我从RC1升级到RC5并收到此错误。

我完成了迁移(引入了一个新的app.module.ts文件,将package.json更改为包含新版本和缺失的模块,最后根据Angular2快速启动示例将main.ts更改为相应的引导)。

我做了一次npm更新,然后做了一个npm过时,以确认安装的版本是正确的,但仍然没有运气。

我最终彻底删除了node_modules文件夹,并重新安装了npm install-瞧!问题已解决。