Wednesday, April 1, 2020

Angular Data-Binding

Data-binding is the core concept of Angular and used to define the communication between a component and the DOM. It is a technique to link your data to your view layer. In simple words, you can say that data binding is a communication between your typescript code of your component and your template which the user sees. It makes easy to define interactive applications without worrying about pushing and pulling data. Data binding can be either one-way data binding or two-way data binding.

Angular provides four types of data binding and they are different on the way of data flowing.
  1. String Interpolation
  2. Property Binding
  3. Event Binding
  4. Two-way binding

String interpolation/ Angular Expression
String Interpolation is a one-way data-binding technique which is used to output the data from a TypeScript code to HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
For example:
{{ data }}
String interpolation adds the value of a property from the component:
<li>Name: {{ }}</li>  
<li>Email: {{ }}</li>  

Property Binding
Property Binding is also a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code.
For example:
<img [src]="imgUrl"/>
<input type="email" [value]="">  

Event Binding
In Angular, event binding is used to handle the events raised from the DOM like button click, mouse move etc. When the DOM event happens (eg. click, change, keyup), it calls the specified method in the component. In the following example, the cookBacon() method from the component is called when the button is clicked:
For example:
<button (click)="cookBacon()"></button>  

Two-way Data Binding
We have seen that in one-way data binding any change in the template (view) was not be reflected in the component TypeScript code. To resolve this problem, Angular provides two-way data binding. The two-way binding has a feature to update data from component to view and vice-versa.
In two way data binding, property binding, and event binding are combined together.
[(ngModel)] = "[property of your component]"  

Note: For two way data binding, we have to enable the ngModel directive. It depends upon FormsModule in angular/forms package, so we have to add FormsModule in imports[] array in the AppModule.