Introduction to Data binding
Data-binding is the mechanism for coordinating the parts of a template with the parts of the component. You can achieve data binding by adding the binding markup to the template HTML. This is how Angular gets to know how a template is connected to the component.
There are four types of data binding in Angular:
- Interpolation
- Property Binding
- Event Binding
- Two-Way Data Binding
Interpolation
Interpolation is used to directly access the properties present in a component into the HTML template.It is used to resolve an expression.
- It can resolve concatenation or numerical expressions.
- It can resolve the properties defined in the class having scope as public or default.
- Interpolation don't work for properties marked as private in component class.
The following example demonstrates interpolation.
The output can be seen on the browser as:
As can be seen from the output plus operator with a numeric value performs addition while with string value performs concatenation.
Property Binding
Property Binding is a single way data binding in which you can bind your class level properties to the components view.
The syntax for property binding is:
[attribute-name] = 'property-name' OR??? [ngModel] = 'property-name'
For Example:
Any change in title property will change the input value, however reverse is not possible since it is single way databinding.
Please note, to use ngModel you need to import FormsModule in your root Module.
Event Binding
Event Binding provides you with a way to capture various types of events and execute some functionality if such events occur.
The syntax for event binding is:
(eventNameToBeCaptured) = "someFunction()" or (ngModelChange) = "someFunction()"
Please note, to use ngModelChange you need to import FormsModule in your root Module.
For Example:
Two-Way Data Binding
Two way data binding can bind class level property with component view and any change from either end will be reflected on both the sides instantly.
The syntax for two-way data binding is:
[(attribute-name)] ='properties-name'
For Example:
Any change in the input value of two-way data binding will also change the value displayed using interpolation and vice versa.
<input type="text" [(ngModel)] ="title1">
The above code is equivalent to:
<input [ngModel]="title1" (ngModelChange)="title1=$event">
You can find the reference of above example here: https://github.com/nagmabano/AngularApplication/tree/master/my-app/src/app/header
This was all about the types of data binding in Angular. Feel free to share your experiences in the comments section while working with Angular's data binding.