Angular Two-Way Data Binding + NgModel Example

NgModel

xyz

xyzChange

value

input

NgModel

ngModel

ngModelChange

xyz

xyzChange

ngModel

Software Used

Two-Way Binding Syntax

<msg-app [(cdMsg)] ="msg"> </msg-app>

<msg-app bindon-cdMsg ="msg"> </msg-app>

xyzChange

NgModel

NgModel

NgModel

FormsModule

imports

@NgModule

NgModel

<input [(ngModel)] ="myMsg"/>

Create Component and Module

import {Component} from '@angular/core'; import {Employee} from './employee'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { //Property for MsgComponent and AliasComponent msg = 'Hello World'; //Property for AliasComponent city = 'Varanasi'; //Property for TextSizeComponent textSize = 20; //Property for SelectBoxComponent colors = ['RED', 'GREEN', 'YELLOW']; //Property for CaseComponent emp = new Employee(1, 'Mohan Das'); }

<b>1. msg-app</b><br/><br/> <div> <msg-app [(cdMsg)] ="msg"> </msg-app> <msg-app bindon-cdMsg ="msg"> </msg-app> <msg-app [cdMsg] ="msg" (cdMsgChange) = "msg=$event" > </msg-app> <p>{{msg}}</p> </div> <b>2. text-app</b><br/><br/> <div> <text-app> </text-app> </div> <br/><b>3. alias-app</b><br/><br/> <div> <alias-app [(myCity)] ="city"> </alias-app> {{city}} </div> <br/><b>4. size-app</b><br/><br/> <div> <size-app [(cdTextSize)] ="textSize"> </size-app> <p [style.font-size.px] = "textSize">Hello World!</p> </div> <b>5. select-app</b><br/><br/> <div> <select-app [cdColors] ="colors"> </select-app> </div> <b>6. case-app</b><br/><br/> <div> <case-app [(myName)] ="emp.name"> </case-app> <p>{{emp.name}} </p> </div> <b>7. upper-case-app</b><br/><br/> <div> <upper-case-app> </upper-case-app> </div>

import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {FormsModule} from '@angular/forms'; import {AppComponent} from './app.component'; import {MsgComponent} from './msg.component'; import {AliasComponent} from './alias.component'; import {TextBoxComponent} from './textbox.component'; import {TextSizeComponent} from './textsize.component'; import {SelectBoxComponent} from './selectbox.component'; import {CaseComponent} from './case.component'; import {UpperCaseComponent} from './uppercase.component'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [AppComponent, MsgComponent, AliasComponent, TextBoxComponent, TextSizeComponent, SelectBoxComponent, CaseComponent, UpperCaseComponent], bootstrap: [AppComponent] }) export class AppModule { }

FormsModule

imports

@NgModule

NgModel

Two-Way Binding between Components

app.component.ts

msg = 'Hello World';

msg.component.ts

@Input() cdMsg : string; @Output() cdMsgChange = new EventEmitter<string>();

msg.component.html

cdMsg

<input [value] = "cdMsg" (input)="update($event.target.value)"/>

update()

update(val : string) { this.cdMsg = val; this.cdMsgChange.emit(this.cdMsg); }

emit()

app.component.html

<msg-app [(cdMsg)] ="msg"> </msg-app>

<msg-app bindon-cdMsg ="msg"> </msg-app>

<msg-app [cdMsg] ="msg" (cdMsgChange) = "msg=$event" > </msg-app>

import {Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'msg-app', templateUrl: './msg.component.html' }) export class MsgComponent { @Input() cdMsg : string; @Output() cdMsgChange = new EventEmitter<string>(); update(val : string) { this.cdMsg = val; this.cdMsgChange.emit(this.cdMsg); } }

<input [value] = "cdMsg" (input)="update($event.target.value)"/>

Two-Way Binding with NgModel in Input Text Box

NgModel

NgModel

FormsModule

FormsModule

imports

@NgModule

module.ts

textbox.component.ts

myMsg = 'Hello World!';

ngModel

textbox.component.html

<input [(ngModel)] ="myMsg"/>

[(ngModel)]

myMsg

myMsg

ngModel

<input bindon-ngModel ="myMsg"/>

NgModel

ngModel

ngModelChange

<input [ngModel] ="myMsg" (ngModelChange) ="myMsg=$event"/>

ngModel

<input [value] ="myMsg" (input)="myMsg=$event.target.value"/>

import {Component} from '@angular/core'; @Component({ selector: 'text-app', templateUrl: './textbox.component.html' }) export class TextBoxComponent { myMsg = 'Hello World!'; }

<input [(ngModel)] ="myMsg"/> <br/> <input bindon-ngModel ="myMsg"/> <br/> <input [ngModel] ="myMsg" (ngModelChange) ="myMsg=$event"/> <br/> <input [value] ="myMsg" (input)="myMsg=$event.target.value"/> <br/> {{myMsg}}

app.component.html

textbox.component.ts

<div> <text-app> </text-app> </div>

Two-Way Binding with Input and Output Property Aliasing

@Input

@Output

@Input

@Output

import {Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'alias-app', templateUrl: './alias.component.html' }) export class AliasComponent { @Input('myCity') strCity : string; @Output('myCityChange') cityObj = new EventEmitter<string>(); emitCity() { this.cityObj.emit(this.strCity); } }

strCity

myCity

cityObj

myCityChange

strCity

[(ngModel)]

emitCity()

<input [(ngModel)] ="strCity" /> <button (click)="emitCity()" >Update</button>

app.component.html

<div> <alias-app [(myCity)] ="city"> </alias-app> {{city}} </div>

app.component.ts

city

city = 'Varanasi';

alias.component.html

Two-Way Binding between Components to Change Style

app.component.ts

textSize

textsize.component.ts

app.component.ts

app.component.ts

textSize = 20;

app.component.html

textsize.component.ts

<div> <size-app [(cdTextSize)] ="textSize"> </size-app> <p [style.font-size.px] = "textSize">Hello World!</p> </div>

textsize.component.ts

import {Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'size-app', templateUrl: './textsize.component.html' }) export class TextSizeComponent { @Input() cdTextSize : number; @Output() cdTextSizeChange = new EventEmitter<number>(); plus() { this.cdTextSize = this.cdTextSize + 1; this.emitSize(); } minus() { this.cdTextSize = this.cdTextSize - 1; this.emitSize(); } emitSize() { this.cdTextSizeChange.emit(this.cdTextSize); } }

<button (click)="plus()"> + </button> <button (click)="minus()"> - </button>

Two-Way Binding with NgModel in Select Box

NgModel

import {Component, EventEmitter, Input} from '@angular/core'; @Component({ selector: 'select-app', templateUrl: './selectbox.component.html' }) export class SelectBoxComponent { @Input() cdColors : Array<string> myColor = 'GREEN'; }

<!--select [value] ="myColor" (change)="myColor=$event.target.value" --> <select [(ngModel)] ="myColor"> <option *ngFor = "let color of cdColors" [value] = "color"> {{color}} </option> </select> <p [style.color] = "myColor"> Hello World!</p>

NgModel

myColor

myColor

NgModel

<select [value] ="myColor" (change)="myColor=$event.target.value" >

selectbox.component.ts

app.component.html

<div> <select-app [cdColors] ="colors"> </select-app> </div>

app.component.ts

colors

colors = ['RED', 'GREEN', 'YELLOW'];

Two-Way Binding between Components using Object Property

export class Employee { constructor(public id : number, public name : string) { } }

app.component.ts

Employee

name

Employee

case.component.ts

name

Employee

app.component.ts

import {Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'case-app', templateUrl: './case.component.html' }) export class CaseComponent { @Input() myName : string; @Output() myNameChange = new EventEmitter<string>(); changeCase(val:string) { if (val == 'upper') { this.myName = this.myName.toUpperCase(); } else { this.myName = this.myName.toLowerCase(); } this.myNameChange.emit(this.myName); } }

<input type="radio" name="case" (click) = "changeCase('upper')">Upper Case<br> <input type="radio" name="case" (click) = "changeCase('lower')"> Lower Case<br>

app.component.html

<div> <case-app [(myName)] ="emp.name"> </case-app> <p>{{emp.name}} </p> </div>

app.component.ts

Employee

emp = new Employee(1, 'Mohan Das');

Two-Way Binding with NgModel using Object Property

NgModel

name

Employee

name

Employee

import {Component} from '@angular/core'; import {Employee} from './employee'; @Component({ selector: 'upper-case-app', templateUrl: './uppercase.component.html' }) export class UpperCaseComponent { employee = new Employee(100, 'Mahesh Sharma'); toUpper(val:string) { this.employee.name = val.toUpperCase(); } }

<input [(ngModel)] ="employee.name"/>{{employee.name}} <br/><input [ngModel] ="employee.name" (ngModelChange) ="toUpper($event)"/>{{employee.name}}

ngModelChange

uppercase.component.ts

app.component.ts

<div> <upper-case-app> </upper-case-app> </div>

Run Application

Reference

Download Source Code

This page will walk through Angular two-way data binding andwith examples. Using two-way binding, we can display a data property as well as update that property when user does changes. We can achieve it in component element and HTML element both. Two-way binding uses the syntax asorkeyword. Two-way binding uses the syntax of property binding and event binding together. Property binding uses the syntax as bracketorand event binding uses the syntax as parenthesisorand these bindings are considered as one-way binding. Two-way binding works in both direction setting the value and fetching the value. Two-way binding uses a specific name pattern. Event name should be property addingkeyword as suffix. So if we have a propertythen event name should be. In component property binding and custom event binding we create our own property name and event name asin binding. So we can follow the naming pattern. But in HTML element there are in-built names asin binding such asin property binding andin event binding. So here the role ofdirective comes into the picture to work as bridge that enables two-way binding to HTML elements. It provides the required name pattern ofasin property binding andin event binding. When two-way binding is between components at component element level and input property name isand output property name isthen thein two-way binding will be written as. If two-way binding is taking place at HTML element level such as in input box or select box then we will useforname as. Now find the complete example of two-way binding step-by-step.Find the software used in our demo.1. Angular 9.1.112. Node.js 12.5.03. NPM 6.9.0The syntax for two-way binding is as follows.1.is two-way binding whereis to set value from source to target andis to set value from target to source. For example find the code snippet.2.is also two-way binding syntax wheresets value from source to target andsets value from target to source. For example find the code snippet.3. Usekeyword as suffix in input variable name to create output variable. Suppose input variable name isthen output variable name will be4.is a two-way binding usingdirective. We will usein HTML element where we set a specific element property and listen for an element change event . We will use two-way binding within text box and select box in our example.can set only data-bound property. To usewe need to importand add it toattribute ofin our module file. Now for the example of two-way data binding usingfind the code snippet.In our example we have a parent component that will call many child components. Find the parent component and its HTML template.Here we are using two-way binding with many component elements . We will discuss one by one in our examples. Now find the module used in our example.Here we are importingand adding it toattribute ofso that we can usein our code.Here we will provide example for two-way data binding between components. We will discuss a scenario in which a string property of parent component will be sent to child component. In child component that property will be updated using text box. Parent component will listen the changes. We will provide step by step two-way binding example between the two components.1. Create a string property in2. Create input and output property inWe will observe that output property name is3. Inwe will updateusing a text box.4. For any input in text box,method will be called.In the above code we are callingmethod.5. Inwe are performing two-way binding.Usingwe can achieve the same goal.If we do not use two-way binding then same goal can be achieved using component property binding and custom event binding.Now find the files used in our example.We will perform here two-way binding in input text box. The scenario is that a text box will display data using component property and on the change of text box value, component property will also get changed. Find the steps for two-way binding using1. To work withwe need. Ensure that in module file we have importedand added it toattribute of. In my example module file is2. Create a property in3. Usefor two-way binding incan set only data-bound property. When we run the code the text box will display the value of. When the user changes the value in text box thenwill also get changed. Usingwe can useas follows.4. If we want to useas property binding and event binding separately then we need to useandas follows.Here we will observe that the event name pattern will useas suffix. If we want to achieve same without, then we do as follows.Now find the files used in our example.Inwe will callWe will understand here how to use two-way binding between components whenanddecorators are using property name aliasing. The property name pattern will be followed in alias name for two-way binding.Now find the code that are usinganddecorators.Look at the code of component. The name pattern for two-way binding is being followed in aliases of properties but not in actual property names. The alias for input propertyisand the alias for output propertyis. Here event name alias is input property name alias addingas suffix. So we can perform two-way binding with these aliases.is getting updated by two-way binding usingin text box. On click of button,will be called. Find the HTML template.Now we are performing two-way binding inTwo-way binding is using aliases and that are following name pattern i.e event name should be input property name addingas suffix for two-way binding between components.Inwe are initializing ourproperty.The above property value will get updated when we change value in text box ofFor the demo of two-way binding, now we will provide an example in which we have two buttons as plus(+) and minus(-). On click of these buttons we will change the font size of a text. Here we are using component element two-way binding.will initialize a font size inproperty and it will send it to. Using plus and minus button we will increase and decrease its value that will also get updated inTo achieve it we have created the property for size with some initial value inInwe are callingby creating component element with two-way binding as follows.Now find thefile and its HTML template file.Here we will provide example for two-way binding in which we will show how to usewith HTML select box. The scenario is that an array of colors will be populated by select box. A default color initialized by component property will be selected initially in select box and a sample text is using that color. On change of color in select box, the color of text will change.Here we are usingfor two-way binding. We will observe thatis initially providing a default color as selected in select box and on change of color selection the value ofis getting changed.If we do not want to usewe will do as follows.We are usinginas follows.is defining the array propertyHere we will use an object property for two-way binding between components. We have a class as follows.Now our scenario is that we will change a given text as uppercase and lowercase on click of two radio button. Inwe are creating an object ofclass. Using two-way binding we will sendproperty ofclass to. In this component we change the text as lowercase and uppercase on the click of radio button and then send this changed data toproperty ofclass in. Now find the code to change lower and upper case.We are performing two-way binding inas follows.Inwe are instantiatingclass as follows.Here we will usefor two-way binding with object property. Our scenario is that we will create text box which will display value ofproperty ofclass and on change of text box value theproperty ofclass will also get updated.If we usefor event binding then we can call our component method and can pass data to it. Now we will useinas follows.To run the application, find the steps.Download source code using download link given below on this page.Use downloadedin your Angular CLI application. To install Angular CLI, find the link Runusing command prompt.Access the URLFind the print screen of the output.Output description is as follows.When we change value in any text box then all text box value will get updated and at the same time text outside the text box will also get changed.When we change value in any text box then all text box value will get updated and at the same time text outside the text box will also get changed.When we change value in text box and click on update button, the text will also get changed.On click of button the size of text "Hello World!" will change. When we click plus (+), text size will increase and when we click minus (-) , text size will decrease.When we select the color from select box then that color will also be applied on text color of "Hello World!".When we click upper case radio button, the name will appear in upper case and when we click lower case radio button, the name will appear in lower case.In first text box when we change value, both the text box and text outside text box will get changed. When we change value in second text box, both the text box and text outside text box will get changed as well as they will be converted in upper case.I am done now. Happy Angular learning!