Two Way Data Binding In Angular 2 - Part10

From our previous article, we learned about Event Binding in Angular 2.

I recommend you go through my previous articles from the beginning for the better understanding.

References

In this article, we are going to learn 2 way Data Binding in Angular.

Let’s say the user is entering a form and it is possible in Angular to have live preview through data binding.

Thus, we can change a data property and simultaneously display the data property in our view.

For example, let’s say we have two input fields given below.

 
 
Code 

  1. export class RathrolaComponent {  
  2.     public title = "Tutorials from Rathrola";  
  3.     public fname;  
  4.     public lanme;  
  5. }   

In Angular, whenever we have to make use of Two Way data binding, then we make use of ng-module Directive.

Thus, we assign to the ng model the property to which we want to bind and it looks, as shown below.

 
 
Code

  1. @Component({  
  2.     selector: "my-tuts",  
  3.     template: `<h2>{{title}}</h2>  
  4. <input type="text" [(ngModel)]="fname">  
  5. <input type="text" [(ngModel)]="lname">`  
  6. })   

ng model has to be wrapped with {} and [] brackets, as shown above.

If you recollect, we had event binding specified by {} and property data binding specified by [] brackets.

Thus, this is a Two Way data binding. We are going to be making use of Event binding and Property data binding.

Whenever the first name and last name property changes, the view is getting the updates and when the view changes, the property gets updated.

Let's use interpolation to display live preview, as shown below.

 

Code

  1. FullName: {{fname}} {{lname}}`  

Output

 

This is how Two Way data binding works and in my next article, I shall start teaching you about Directives.


Similar Articles