Data Binding in Angular: Types, Role, Concepts, & More
As of 2022, Angular is one of the top 10 web frameworks used by front-end developers globally. Numerous large companies, including BMW, Forbes, Google, Adobe, PayPal, etc., use it for web application development. This framework was created by Google, making it a highly reliable and credible platform. In this blog, we will talk about data binding in Angular, one of the key ideas that makes it possible to connect the user interface (UI) and the application’s data.
What is Data Binding in Angular?
Angular is a development platform built on TypeScript, a superset of JavaScript. The purpose of this development framework is to build dynamic web applications. Data binding is the process carried out behind displaying data in an application’s view. This mechanism establishes a link between the application’s user interface and the displayed data. It simply defines the relationship between various software development components and their views to create interactive and dynamic applications.
Join our full stack developer course with placement guarantee today and lock in your internship along with a guaranteed total stipend of 35,000!
How Does Data Binding Work in Angular?
Data binding in Angular is a special feature that allows the interaction of data between the component class and its corresponding user interface (UI) template. The component class specifies the UI logic by creating properties and methods. These properties and methods are used in the view template of the component. Component class property changes affect both views and result in reflected changes in web applications.
For example, there is a text box on the webpage. Whenever a user enters a value in that text box, it gets assigned to a corresponding property in the component class. In this case, data will transfer from the view template to the component class. This is how data binding in Angular takes place.
Through data binding, the user interface can be dynamically updated as the application’s data (the model) and user interactions (the view) change. This particular feature rules out the possibility of manual manipulation in the DOM (Data Object Model), which is a programming interface that represents the structure of an HTML document.
Role of AngularJS Controller in Data Binding
As the name suggests, it controls the data-binding process and allows the user to interact with the web application by handling all the user input and output.
- It facilitates the data-binding process between the model (data) and the view (user interface).
- It also supports two-way data binding between them, which means any changes in the view (input) will naturally update the data in the Controller, and changes in the Controller will update the view in the same manner. This is achieved through the ng-model directive.
- It also handles the triggers or events initiated by users in the view.
- It helps in data transformation to present the data in a readable format in the view.
Special Binding Concepts Used in Angular
To bind data to HTML elements and manipulate the DOM (Document Object Model) efficiently, the following concepts are used:
Attribute Binding
This concept in Angular’s data-binding helps to bind an element attribute from a component class to a view template. It can be used for any existing properties or custom attributes. The data flow is one-way from component class to view.
It dynamically updates an element’s appearance or behavior based on a condition, such as hiding an element unless a user is logged in or changing its color based on status. To bind to an attribute, square brackets are used around the attribute name.
Class Binding
The class binding applies CSS classes to an element based on the component’s data. It either adds or removes CSS classes from an element based on certain conditions. It is also defined in square brackets.
Style Binding
In style binding, CSS properties are used to enable the dynamic application of inline styles to HTML elements based on the data in the application’s component. This binding is also denoted with square brackets.
ngModel
It is a directive in Angular to facilitate a two-way data binding process (send and receive data) between the view and the model. Whenever there is any change in the view, an automatic update happens in the model. For instance, you could link your data model to the “First name” and “Last name” text boxes in the view using the ng-model directive.
Types of Data Binding in Angular
Angular offers two types of data binding – one-way data binding and two-way data binding. Let us discuss these two data-binding mechanisms in detail.
One-Way Data Binding in Angular
In one-way binding, the data flow is unidirectional, either from the component class to the view or from the view to the component class. It enables accessing a component class property in its corresponding view template and is achieved by interpolation and property binding in Angular. The flow of data from the view template to its corresponding class component is done through Event Binding.
Use of brackets to bind data:
- Two types of brackets are used to bind data from the component class to the view, either “[ ]” or “{{ }}”, and from the view to the component class, ().
Interpolation Binding
It is also called “String Interpolation” and refers to embedding an expression within the double curly braces “{{ }}” to specify the binding expression. This type of one-way data binding allows the user to bind data from the component class to the corresponding view template. It transfers data from the TypeScript code to an HTML template (view). It means that with this method, an expression can be put in between some text and get the value of that expression.
Interpolation binds the text to the expression value.
The syntax for interpolation binding is:
{{ expression }}
Example of Interpolation Binding
Let us take a component with a variable named “currentEmployee”.
// Component.ts
currentEmployee = 'Michael';
Here, the component class (component.ts) is defined with a TypeScript class, and the class contains a property name, “currentEmployee”, with the value ‘Michael’. This property holds the name of the current employee.
Interpolation is used to display the value of the variable as follows:
<!-- Component.html -->
<h3>Current employee: {{ currentEmployee }}</h3>
Here is the component template (Component.html) that defines the view of the component in the application’s user interface. “<h3> is the heading element that contains the expression “{{ currentEmployee }}. The interpolation binding replaces the expression {{ currentEmployee}} with the value of the “currentEmployee” property of the class component.
Output
<h3>Current employee: Michael</h3>
Here, the heading will read “Current employee: Michael”.
Property Binding
This type of data binding in one direction allows binding the property or method of a component class to an HTML element in the same view. Here, the data flows from the component class to the view template. This binding mechanism mainly sets the properties for HTML elements.
Using property binding, the attribute of an HTML element is found in the property or method of a component class. Toggle functionality and data sharing between components are both possible with this property binding. The syntax uses square brackets “[ ]” for data binding.
The syntax for Property Binding is:
<target-element [binding-target]=”binding-source”></target-element>
Here, the “target-element” is the HTML element where you want to bind the property. The “binding-target” is the target property of the HTML element where you want to bind the component’s value, and it is enclosed in square brackets, [ ]. The “binding-source” is the component’s property that holds the value to bind to the target property.
Example of Property Binding
Here is an example of how to bind the component’s “topic” property to the “topic” attribute of the <h1> element.
<h1 [topic]="topic">Life Sciences!</h1>
In this example, <h1> is the target element. The value of the “topic” property in the component is set as the value of the “topic” attribute in the element <h1>.
Output
Life Sciences
Event Binding
With the event binding mechanism, the data flows from the view template to the component class. This takes place when an event is triggered, which is a webpage event. For instance, it could be simply a mouse click on the view, and the view sends the data to update the component’s property or method. This type of binding allows binding webpage events to a component’s property or methods.
The syntax of event binding is:
<target-element (eventName)="methodName()"></target-element>
In the syntax, “target-element” is the HTML element to which the event will bind, “eventName” is the trigger that causes the event on a webpage, and “methodName()” is the method in the Angular component that is executed when the event occurs.
Example of Event Binding
Let us see an example where the event is a button click. Consider “onButtonClick” as the method that will execute when the button is clicked.
First, define the method “onButtonClick” in the component class (Component.ts).
// Component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
})
export class ExampleComponent {
// Method to be executed on button click
onButtonClick() {
alert('Button clicked!');
}
}
Then, execute event binding as follows
<button (click)="onButtonClick()">Click Me!</button>
Output
An alert “Button Clicked” will appear on the execution of the event “onButtonClick”.
Two-Way Data Binding in Angular
This type of binding allows binding data in two directions, that is, from component class to view template and vice-versa. It is achieved through a combination of property binding and event binding. Therefore, any change in the component class will reflect in the template, and any change in the view will reflect in the component class. Use “[( )]” to bind data in the two-way sequence.
The syntax for two-way data binding is:
<input type="text" [(ngModel)]="componentProperty" />
The combination of event and property binding is done as (event binding) wrapped with [property binding]. Here, [(ngModel)] is the built-in directive to bind the input element, such as “text” in this syntax. As this name suggests, “componentProperty” is the property of the component that holds data that you want to bind to the input element.
Example of Two-Way Data Binding in Angular
Let us consider a component property named ‘username’. The component will include an input field for the user to enter their username, as well as a greeting message based on the username entered.
First, define the component class (component.ts) as follows:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'],})export class AppComponent { username: string = ''; // Initialize username property}
Second, define the component template (component.html) as follows:
//Two-Way Data Binding Example<input [(ngModel)]="username" /><p *ngIf="username">Hello, {{ username }}!</p>
Output
"Hello, [user name entered]"
Learn Angular to improve your understanding of its components.
Conclusion
This blog helped you understand the different ways of binding data between the component and the view. Data Binding in Angular is important to create user-friendly interfaces and interactive applications. It helps provide real-time updates and increases the performance of the applications.
FAQs
There are two types of data binding provided in Angular:
a) One-Way Data Binding: This includes Interpolation, Property Binding, and Event Binding.
b) Two-Way Data Binding: It is a combination of Property Binding and Event Binding.
The Angular 9 framework’s data binding feature facilitates the connection of various modules by performing simultaneous actions between them.