Two-way binding doesn't work

2.2k views Asked by At

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

There are 1 answers

1
Sachila Ranawaka On BEST ANSWER

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 { }