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.
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
- export class RathrolaComponent {
- public title = "Tutorials from Rathrola";
- public fname;
- public lanme;
- }
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
- @Component({
- selector: "my-tuts",
- template: `<h2>{{title}}</h2>
- <input type="text" [(ngModel)]="fname">
- <input type="text" [(ngModel)]="lname">`
- })
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
- FullName: {{fname}} {{lname}}`
Output
This is how Two Way data binding works and in my next article, I shall start teaching you about Directives.