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

当前回答

对于我的场景,我必须将[CommonModule]和[FormsModule]导入到我的模块

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

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }

其他回答

如果在正确导入FormsModule后仍然出现错误,请检查您的终端或(windows控制台),因为您的项目未在编译(因为可能是其他错误),并且您的解决方案尚未反映在浏览器中!

在我的情况下,我的控制台出现了以下不相关的错误:

类型“ApiService”上不存在属性“retrieveGithubUser”。

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

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

在app.module文件中导入FormModule

import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] })

有时,即使我们已经导入了BrowserModule、FormsModule和其他相关模块,我们仍然可能会收到相同的错误。

然后我意识到我们需要按顺序导入它们,这在我的案例中是缺失的。因此,顺序应该类似于BrowserModule、FormsModule和ReactiveFormsModul。

根据我的理解,功能模块应该遵循Angular的基本模块。

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

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

对于我的场景,我必须将[CommonModule]和[FormsModule]导入到我的模块

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

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }