Data Binding in Angular
Data binding is an important concept in Angular that allows communication between a component class and its view template. It enables the transfer of data from the component to the view and vice versa.
Types of Data Binding
- One-Way Data Binding: Data flows in one direction (Component → View or View → Component).
- Two-Way Data Binding: Data flows in both directions simultaneously.
One-Way Data Binding
One-way data binding can be classified into two types:
- From Component to View: Achieved using String Interpolation and Property Binding.
- From View to Component: Achieved using Event Binding.
Example: String Interpolation
String interpolation allows data to be displayed in the view using double curly braces {{ }}
.
// my-component.ts
export class MyComponent {
title = 'Angular Data Binding';
}
<!-- my-component.html -->
<h1>{{ title }}</h1>
Example: Property Binding
Property binding binds a component property to an HTML element attribute.
// my-component.ts
export class MyComponent {
isDisabled = true;
}
<!-- my-component.html -->
<button [disabled]="isDisabled">Click Me</button>
Example: Event Binding
Event binding listens for user actions and updates the component.
// my-component.ts
export class MyComponent {
message = '';
onClick() {
this.message = 'Button clicked!';
}
}
<!-- my-component.html -->
<button (click)="onClick()">Click Me</button>
<p>{{ message }}</p>
Two-Way Data Binding
Two-way data binding enables real-time synchronization between the component and the view using ngModel
.
// my-component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
})
export class MyComponent {
username = '';
}
<!-- my-component.html -->
<input [(ngModel)]="username" placeholder="Enter your name">
<p>Hello, {{ username }}!</p>
Conclusion
Data binding is a powerful feature in Angular that enables seamless communication between the component class and the view template. We have explored one-way and two-way data binding with practical examples.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.