Angular 2:模板解析错误:无法绑定到'ngModel',因为它不是'input'的已知属性

kho*_*ang 8 angular

当我使用双向绑定[(ngModel)]时,我收到此消息

Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.
Run Code Online (Sandbox Code Playgroud)

我知道导入FormsModule是为了解决这个问题,因为很多人都来到这里.但是,我确实导入了FormsModule,但它没有帮助,问题仍然存在

当然,我的代码还有其他问题.你能脱光吗?这是我的app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { ValidationModule } from './validation/validation.module';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.module.routing';

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

}
Run Code Online (Sandbox Code Playgroud)

这是我的app.routing.module.ts

import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'

import { Home1Component } from './home1.component';
import { Home2Component } from './home2.component';

const appRoutes = [
  { path: 'home1', component: Home1Component },
  { path: 'home2', component: Home2Component },
  { path: 'validation', loadChildren: './validation/validation.module#ValidationModule'}
];

@NgModule({
    declarations:[
        Home1Component,
        Home2Component
    ],
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports:[
        RouterModule
    ]
})

export class AppRoutingModule {

}
Run Code Online (Sandbox Code Playgroud)

这是我的HTML

<h1> home 1 </h1>
<form>
    <input [(ngModel)]="currentHero.name">
    <button type="button" (click)="onOkClicked()">Ok</button>
</form>
Run Code Online (Sandbox Code Playgroud)

我在这里附上我的源代码,我正在使用angular-cli 源代码

Gün*_*uer 5

您需要FormsModule在使用其指令的模块中添加导入:

@NgModule({
    declarations:[
        Home1Component,
        Home2Component
    ],
    imports: [
        RouterModule.forRoot(appRoutes),
        FormsModule, // <<<=== missing
    ],
    exports:[
        RouterModule
    ]
})
Run Code Online (Sandbox Code Playgroud)


Yoa*_*man 2

如果您想使用反应式表单,则需要添加:ReactiveFormsModule

@NgModule({
    declarations:[
        Home1Component,
        Home2Component
    ],
    imports: [
        RouterModule.forRoot(appRoutes),
        ReactiveFormsModule, 
    ],
    exports:[
        RouterModule
    ]
})
Run Code Online (Sandbox Code Playgroud)