Data Binding

Overview

Data binding is a fundamental concept in modern web development, and it plays a pivotal role in creating dynamic and interactive web applications. In the context of Angular, a popular JavaScript framework, data binding is a powerful mechanism that allows developers to establish a connection between the user interface and the application's underlying data. This connection ensures that changes in one are automatically reflected in the other, creating a seamless and responsive user experience.

What is Data Binding?

Data binding in Angular allows us to communicate between a component class and its corresponding view template(HTML).

Types

In Angular, there are primarily two types of data binding: one-way binding and two-way binding. Here's an explanation of each:

One-Way Binding:

One-way binding refers to unidirectional flow of data from the component to the template or from the template to the component. In one-way binding, changes in one direction do not affect the other. Angular provides several ways to achieve one-way binding:

Interpolation = Interpolation is used to display dynamic data in your templates. It's one-way because it only displays data from the component to the template, and changes in the template do not affect the component.

<p>{{ greeting }}</p>

Property Binding =  Property binding allows you to set the properties or attributes of HTML elements dynamically. Changes in the component's property affect affect the template, but changes in the template do not propagate back to the component.

<img [src]="imageSource">

Event Binding = Event binding enables you to listen to and respond to events in the template by invoking methods in the component. Changes occur when the user interacts with the template, but the template itself doesn't change the component's data.

<button (click)="handleClick()">Click me</button>

Two-Way Binding:

Two-way binding establishes a bidirectional flow of data between the component and the template. Changes in the component's property automatically update the template, and changes in the template are propagated back to the component. Angular provides a specific mechanism for two-way binding using the ngModel directives:

The ngModel directive is used primarily in forms to bind input elements to component properties. It allows both the template and the component to stay in sync, making it a bidirectional, or two-way, binding mechanism.

 <input [(ngModel)]="userInput">

It's important to note that to use two-way binding with ngModel, you need to import the FormModule from @angular/forms in your Angular module.