Two way data Binding in Angular 4
Types of Data Binding in Angular 4
Three Types :
1.No Binding
Example : <input name=”fname” ngModel>
-
One-Way
Example: <input name=”fname“ [ngModel]=”fname”>
-
Two-Way
Note: formmodule must be included in app.module.ts
Example : <input name=”fname” [ngModel]=”fname“ (ngModelChange)=”fname=$event”>
<input name=”fname” [(ngModel)]=”fname”>
Example Source Code :
Step 1: First Create new component two-way-binding.
cd src/app
ng g c two-way-binding –flat -is -it
Step 2: Write following code into the newly generated component.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: ` <p> two-way-binding Works! </p> <input type='text' [(ngModel)]=fathername /> <input type='text' [(ngModel)]=fathername /> <span>{{fathername}}</span> <hr> <h3>Another Way</h3> <input [ngModel]="fathername" (ngModelChange)="fathername=$event"> <input [ngModel]="fathername" (ngModelChange)="fathername=$event"> <span>{{fathername}}</span> `, styles: [] }) export class TwoWayBindingComponent { fathername: string ; }
Step 3: Update( Pass references of the newly created component into app.component.ts and app.module.ts ) app.component.ts
import { Component , EventEmitter, Output } from '@angular/core'; import { MycomponentComponent } from './mycomponent.component'; import { TwoWayBindingComponent } from './two-way-binding.component'; @Component({ selector: 'app-root', template: ` <h2>sdsd</h2> <app-mycomponent (clicked)="onClicked($event)"></app-mycomponent> <p>{{childdata}}</p> <h2>Two Way Data Binding </h2> <app-two-way-binding></app-two-way-binding> ` }) export class AppComponent { childdata= ''; onClicked(value: string) { this.childdata = value; } }
app.module.ts:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { MycomponentComponent } from './mycomponent.component'; import { TwoWayBindingComponent } from './two-way-binding.component'; @NgModule({ declarations: [ AppComponent, MycomponentComponent, TwoWayBindingComponent ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Execute :
ng serve –open
Output: