🅰️ Angular Q7 / 125

What is data binding? Explain its types.

AI-Powered Answer ✓ Answered

Data binding is a core concept in Angular that allows you to establish a connection between your application's data (component) and the HTML document (view). It enables communication between these two parts, synchronizing data automatically.

What is Data Binding?

Data binding in Angular provides a mechanism to move data between the Component and the View. It is fundamental for building interactive and dynamic web applications, as it ensures that the UI always reflects the current state of your application's data, and vice versa.

Types of Data Binding

Angular categorizes data binding into two main approaches: One-Way Data Binding and Two-Way Data Binding. Each approach dictates the direction in which data flows between the component and the view.

One-Way Data Binding

One-way data binding means that data flows in only one direction. This typically involves binding data from the component to the view (e.g., displaying component property values) or from the view to the component (e.g., responding to user events).

  • Interpolation (from component to view)
  • Property Binding (from component to view)
  • Event Binding (from view to component)

Interpolation

Interpolation allows you to display a component property value in the view template. It uses double curly braces {{ }} to embed expressions or properties directly into the HTML.

html
<h1>Welcome, {{ userName }}!</h1>
<p>Current count: {{ counter }}</p>

Property Binding

Property binding allows you to bind a value from a component property to a target element's HTML property (e.g., [src], [disabled], [value]). It uses square brackets [] around the target HTML element property.

html
<img [src]="imageUrl" [alt]="imageAltText">
<button [disabled]="isButtonDisabled">Click Me</button>

Event Binding

Event binding allows you to listen for events (like clicks, key presses, or form submissions) in the view and execute a method in the component in response. It uses parentheses () around the target event name.

html
<button (click)="onButtonClick()">Submit</button>
<input (input)="onInput($event)" placeholder="Type here">

Two-Way Data Binding

Two-way data binding provides a way to synchronize data simultaneously between the component and the view. Any changes in the component are reflected in the view, and any changes in the view (typically user input) are immediately updated in the component. Angular's two-way binding is achieved using the [(ngModel)] directive, often referred to as 'banana in a box'.

html
<input [(ngModel)]="searchText" placeholder="Search...">
<p>You typed: {{ searchText }}</p>

Behind the scenes, [(ngModel)] is syntactic sugar for combining property binding ([ngModel]) and event binding ((ngModelChange)) to achieve this two-way synchronization.