This Angular feature keeps the data in sync between view and component. If the data gets changed at the view, the same variable’s state will be changed at the component and vice versa. Data binding is an important feature of Angular as it plays with DOM manipulation. Data binding is of three types, as discussed below
One-way data binding (String Interpolation)
It binds the template data with components in one direction. When you change the variable state in the component, it will reflect in the DOM. This process is also known as String interpolation. The example is shown below.
ts file
export class DataBindingComponent implements OnInit {
example = "String Interpolation Example";
}
html file
<h1>{{example }}</h1>
2. Property Binding
We can bind the properties of DOM elements with the variables of components. This can be achieved under property binding by using
[]
. Here are a few examples.
ts file
export class PropertyBindingComponent {
src:string = “www.shorturl.at/ejMU5”;
}
html file
<img href=”#” [src]="src">
3. Attribute Binding
This is very similar to property binding. We can bind anything with the attributes of DOM elements by this property.
ts file
export class AttributeBindingComponent {
index:number = 0;
}
html file
<input type="text" [attr.index]="index">
We can bind style and class similarly. There are other few ways to bind bi-directional data. This will be explained in the next section of Event Binding.