Data binding is a concept of communication between the component and view. We can bind the data from our component (.ts file) with the view (HTML file). There are four types of data binding in Angular.
- Interpolation
- Property Binding
- Event Binding
- Two-way Data Binding
Interpolation
We use double curly braces to perform String interpolation. We need to place the property from the component within the braces in the HTML file ({{ property }})
. And later this {{ property }} will be replaced by the property value. This is also termed as one-way data binding.
<div> My Name is {{name}} </div>
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { name = 'Angular'; }
Property Binding
We can bind HTML properties with any specified component’s data. The syntax is [property] = “value”
. This is also one-way data binding.
<input type="text" [value]="name">
<div [innerHTML]="data"> </div>
We can also use the interpolation method to perform property binding.
<img src={{imageUrl}} />
Note: When we are using string value in data binding, we will use interpolation but if we are using non-string value in binding then we need to use property binding.
Here for the “checked” property, we are binding a boolean value, so we have to use property binding.
<input type="checkbox" [checked]="isChecked">
Event Binding
We can bind a DOM event with a specified method of the component with event binding. Syntax is (event) = “function”
.
<button (click)="submit()"> Submit </button>
<input type="text" (keyup)="valueChange()">
Two-way Data Binding
In two-way data binding, the data in component and view are in sync. That means if we change the data in the view, the corresponding data in component changes, and this updated component’s data reflect in the view as well.
For two-way binding we use ngModel
. To use ngModel
directive we need to import FormsModule
in the app.module.ts file.
<input type="text" [(ngModel)]="name"> <div> {{name}} </div>
Here when the input value changes, it changes the property “name” value in the component and the same updated value reflects in the div as well.
Now you can start binding data between your view and component and show the appropriate data in the view.
Related
Web Developer by Profession, Blogger by Passion.
JavaScript | React | Next | Angular | Vue | HTML | CSS