Web
Analytics
angular4 two way binding | example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Two way data Binding in Angular 4

 

angular 4 two way binding

Two way data binding angularjs

Types of Data Binding in Angular 4

Three Types :

1.No Binding

Example : <input  name=”fname”  ngModel>

  1. One-Way

Example: <input  name=”fname“   [ngModel]=”fname”>

  1. Two-Way




Note: formmodule must be included in app.module.ts

import { FormsModule } from ‘@angular/forms’;

 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:

 

angular 4 data binding

angular 4 two way data binding example output