- read

Exploring Angular — Part 2: Data Binding

Șener Ali 47

angular data binding
Angular Data Binding

If you missed the previous article on Components, you can catch up right here: Exploring Angular — Part 1: Components.

What is Data Binding?

So, what exactly is Data Binding in Angular? It’s a robust feature that creates a vital connection between your application’s data and the user interface (UI) elements, such as HTML templates. This linkage ensures that changes to your data are mirrored in the UI, and vice versa, simplifying the development process.

Data Binding Categories

As far as I know, there are two types of data binding: one-way binding and two-way binding.

In one-way binding, the data flow within an Angular application follows a single direction, moving from the TypeScript file to the HTML file. You can achieve one-way binding by simply showing a variable’s value in the UI. So, I will focus in this article on the second category of data binding: the two-way binding.

Two-way Data Binding

To illustrate how the two-way data binding works, I will create an input component. Firstly, let’s create the TypeScript file for this.

import { Component } from '@angular/core';

@Component({
selector: 'input-component',
templateUrl: './input.component.html',
styles: [],
})
export class InputComponent {
username = '';
}

As you can see, no styles are added to this component, but feel free to add them according to your design preferences.

Now, we will create the HTML file.

<input [(ngModel)]="username" placeholder="Enter your username" />
<p>{{ username }}</p>

As you can see I used the [(ngModel)] syntax which is used primarily with form input elements like textboxes, checkboxes, and radio buttons. It allows for bidirectional data flow between the component class and the HTML template, ensuring that changes made to the input element by the user are reflected in the component’s data, and vice versa.

To make it all come together, a change is needed in app.module.ts. We must incorporate the FormsModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from…