问题
I'm trying to learn Angular and Angular-CLI. So I created a project with Angular-CLI, which from the beginning seems to run just fine. Now for testing I changed app.component.html file to the following:
<h1>Input your name:</h1>
<input type="text" [(ngModel)]="name">
<p>Your input: {{ name }}</p>
and my app.component.ts accordingly:
...
export class AppComponent {
name = '';
}
I'm getting the error:
Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.
At this point for some reason nothing renders on the page. I tried to change the app.component.html to this:
<input type="text" ng-model="name">
...
Now the page renders correctly, I do see the input box, but as I type I don't see the two-way binding, I don't see the output in my <p>
element.
Why is it happening and how can it be fixed?
回答1:
You just have to import FormsModule
in your app.module.ts
& your issue will get resolved. Something like this.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
来源:https://stackoverflow.com/questions/46251919/two-way-binding-doesnt-work