What is Data Binding in Angular?

It’s a way of communication between TypeScript code and HTML template.

Let’s see an example below. I created a component called “user”.

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {
    username: string = "";

    onResetUsername() {
      this.username = "";
    }
}

We have a variable that stores the value of the “username” and a method that resets this value, it’s a method triggered by a click event in the HTML template.

<div>
    <input type="text" [(ngModel)]="username">
    <button [disabled]="username === ''" (click)="onResetUsername()">Reset</button>
</div>

<div>
    <h2>Welcome {{ username }}!</h2>
</div>

In the HTML template, we have examples of Property Binding, String Interpolation, Event Binding, and Two-Way Binding. Let’s look at each of them.

Property Binding

[disabled]=”username === ””

Needs to receive a true or false value, so we have this verification. It’s something that comes from the TypeScript code to the HTML template. If the value provided is true, the button is disabled.

String Interpolation

{{ username }}

Displays the value of the “username” variable.

Event Binding

(click)=”onResetUsername()”

When clicking the button, the event occurs and calls the onResetUsername() method, which is defined in the TypeScript code. Thus, the event flows from the HTML template to the TypeScript code.

Two-Way-Binding

[(ngModel)]=”username”

It’s the combination of Property Binding and Event Binding, which means it works in both directions.

Don’t forget to use FormsModule, we need it for ngModel to work.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    FormsModule,
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Let’s see the project running:

Author

  • Natan Ferreira

    Hello there, I’m Natan Lara Ferreira, Full Stack Developer Java and Angular since 2016. I’m in Open Finance Brazil project using framework Quarkus and Angular since the beginning 2021. I'm a problem solver, critical thinker and team player.