Two-way binding doesn't work

你说的曾经没有我的故事 提交于 2019-12-08 12:30:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!