我的组件中有一个简单的输入,它使用[(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文件中包含FormModule,以避免无法绑定到ngModel,因为它不是Angular应用程序中输入问题的已知属性。

步骤如下,

打开app.module.ts并添加导入行

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

并将FormsModule添加到导入

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

图1.0(app.module.ts文件)

其他回答

假设您已经创建了一个新的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中导入。

确保[(ngModel)]实际拼写为“ngModel”,大写为M。我花了几分钟没看到这个

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

最近,我发现错误不仅发生在您忘记在模块中导入FormsModule的情况下。在我的案例中,问题出现在以下代码中:

<input type="text" class="form-control" id="firstName"
                   formControlName="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">

我通过更改表单ControlName->name来修复它

<input type="text" class="form-control" id="firstName"
                   name="firstName" placeholder="Enter First Name"
                   value={{user.firstName}} [(ngModel)]="user.firstName">