Angular 2 two way binding using ngModel is not working
Angular has released its final version on 15th of September. Unlike Angular 1 you can use ngModel
directive in Angular 2 for two way data binding, but you need write it in a bit different way like [(ngModel)]
(Banana in a box syntax). Almost all angular2 core directives doesn't support kebab-case
now instead you should use camelCase
.
Now
ngModel
directive belongs toFormsModule
, that's why you shouldimport
theFormsModule
from@angular/forms
module insideimports
metadata option ofAppModule
(NgModule). Thereafter you can usengModel
directive inside on your page.
app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<input type="text" [(ngModel)]="myModel"/>
{{myModel}}
`
})
export class AppComponent {
myModel: any;
}
app/app.module.ts
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 ], //< added FormsModule here
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app/main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
Demo Plunkr
Key Points:
ngModel in angular2 is valid only if the FormsModule is available as a part of your AppModule.
ng-model
is syntatically wrong.- square braces [..] refers to the property binding.
- circle braces (..) refers to the event binding.
- when square and circle braces are put together as [(..)] refers two way binding, commonly called banana box.
So, to fix your error.
Step 1: Importing FormsModule
import {FormsModule} from '@angular/forms'
Step 2: Add it to imports array of your AppModule as
imports :[ ... , FormsModule ]
Step 3: Change ng-model
as ngModel with banana boxes as
<input id="name" type="text" [(ngModel)]="name" />
Note: Also, you can handle the two way databinding separately as well as below
<input id="name" type="text" [ngModel]="name" (ngModelChange)="valueChange($event)"/>
valueChange(value){
}