2017-07-02 68 views
1

我刚开始学习。我app.components.ts文件看起来像这样:Angular 4:无法绑定到'ngModel'

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

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

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    // title = 'app'; 
    name = ''; 
} 

和我app.component.html是这样的:

<input type="text" [(ngModel)]="name"> 
    <p>{{ name }}</p> 

的Javascript控制台是给我以下错误:

compiler.es5.js:1689 Uncaught Error: Template parse errors: 
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("et="_blank" href="http://angularjs.blogspot.ca/">Angular blog</a></h2> 
    </li> 
    <input type="text" [ERROR ->][(ngModel)]="name"> 
    <p>{{ name }}</p> 
</ul> 
"): ng:///AppModule/[email protected]:21 
    at syntaxError (http://localhost:4200/vendor.bundle.js:18052:34) 
    at TemplateParser.webpackJsonp.../../../compiler/@angular/compiler.es5.js.TemplateParser.parse (http://localhost:4200/vendor.bundle.js:29164:19) 
    at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._compileTemplate (http://localhost:4200/vendor.bundle.js:43209:39) 
    at http://localhost:4200/vendor.bundle.js:43129:62 
    at Set.forEach (native) 
    at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._compileComponents (http://localhost:4200/vendor.bundle.js:43129:19) 

...

This页面建议添加FormsModule但是你可以看到它不起作用。

+0

https://plnkr.co/edit/tWWd0bM0HAgThbtQxSao?p=preview它工作正常。但是,如果您使用'plain javascript',则会发现此问题。https://stackoverflow.com/a/41092752/5111904 –

+0

以前发生过此错误。你使用什么角度的版本?你可以把一个笨蛋? – Gary

+0

我正在使用角度4 – Cody

回答

1

你错过了班级AppModule

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

@NgModule({ 
    imports: [FormsModule ], 
    //... 
}) 
export class AppModule {} // <-- do you have this part? 
+0

不,我没有,添加后我仍然收到错误 – Cody

+0

你正在得到什么新的错误? – DeborahK

0

ngModel需要名称为输入:

<input type="text" [(ngModel)]="name" name="nome"> 
相关问题