Tuesday, October 23, 2018

Two way binding in Angular

Two way binding is nothing but the ngModel which we used in AngularJS. As the name indicates two-way binding binds changes in the view to the model and any changes in the model to the view.

Two way binding is represented with a combination of square and curly braces in Angular [(ngModel)]. The property to be bound follows the [()] symbol as follows.

[(ngModel)] = 'productName'

Let us understand two way binding with a simple example, we have a textbox in the view whose value is bound using two-way binding to a property in the component myValue. When the component initializes the value set in the component class will get displayed in the textbox, and when the user changes the value in the textbox the change is reflected in the model, we will show this by displaying the value of property myValue in a label using interpolation.

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  myValue ='Initial value';
}

app.component.html
<div>
  <input type="text" [(ngModel)]="myValue"><br/>
  Latest value of property myValue: <b>{{myValue}}</b>
</div>

In the component class we set the value of the myValue property, in the view template we assign the property to a textbox using ngModel which enables two-way binding. The same property is displayed as a label using interpolation, when the value in the textbox property changes the updated property value will be displayed in the interpolation.




Search Flipkart Products:
Flipkart.com

No comments: