Effective ways of Data-Binding in Angular

Knoldus Blog Audio
Reading Time: 4 minutes

Data-binding is an important concept of Angular. It allows us to define the communication between components and views. Data-binding plays the role of mediator between our Typescript file and Angular Html template for instance.

Generally, data-binding may be one-way or two-way. Angular provides a various way of binding the data

  1. String Interpolation
  2. Property Binding
  3. Event binding
  4. Two-way binding

These four types of data-binding are provided by Angular.

Let’s explore these data-binding one by one

String Interpolation

String Interpolation is a one-way data-binding. It allows us to display data dynamically from typescript file to Html Template. It uses double curly braces to display the data from the component to the view.

app.component.ts file

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'First Angular App';
}

In the above following code or app.component.ts file, we have a variable called “title” which has a string value. Generally, we want to display this title value on the app component HTML view to the user.

Write this line of code in your app.component.html file .

<h1>{{ title }}</h1>

String interpolation resolve it display the tile on page but It is not limited to this , we can also use it for expression evaluation like

Example 1:

<h1>{{ 4 + 5}} </h1>

String interpolation resolve it and display 9 on your page .

Example 2:

app.component.ts file

export class AppComponent {
  title = 'First Angular App';
  num = 10;
  num2 = 20;

  addNum() {
   return this.num + this.num2;
  }
} 

app.component.html file

<h1> Sum is :{{ addNum() }} </h1>

Now run ng serve -o and see the output.

Output

Property Binding

Property binding is also a one-way data-binding, as values go from the component to the template layer, and changes made in the component updates the properties bound in the template.

In Angular applications, we can attach properties to DOM using values declared in the component. Using the square brackets [ ] syntax and we can bind properties to DOM elements. The property to be bound can also be prefixed with bind-.

For example

app.component.ts file

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'First Angular App';
 animal = { name: 'Lion Baby',
           image: 'https://encrypted-tbn0.gstatic.com/images
         q=tbn:ANd9GcR4l7iMNcVcI7v93JGmleqayoDySBJL5uU5iA&usqp=CAU'
 };
}

app.component.html file

<img [alt]="animal.name" [src]="animal.image" />
 
<img bind-alt="animal.name" bind-src="animal.image">

Output

Event Binding

Event Binding in angular is another way of binding, in which we are not binding data from typescript file to Html template. Basically, in event binding, we are handling an event that is raised from the DOM like click on a button, mouseenter, mouseleave, and many more.


Event binding in angular is done by using () inside these parentheses we pass the event that we want to fire.
Event is handled in angular by the following syntax:


(target event name) = “function in TypeScript file”

Bind the target event name within parentheses on the left of an equal sign, and the event handler method or statement on the right.

<button (click)="onShow()">Show</button>

For example

app.component.ts file

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'First Angular App';
 animal = { name: 'Lion Baby',
            image: 'https://encrypted-tbn0.gstatic.com/images?      q=tbn:ANd9GcR4l7iMNcVcI7v93JGmleqayoDySBJL5uU5iA&usqp=CAU'
 };

  onShow(): void {
    console.log( 'Event binding Working');
  }
}

app.component.html file

<h1>{{ title }}</h1>
<img [alt]="animal.name" [src]="animal.image" />
<button (click)="onShow()">Show</button>

Output:

Alternatively, in event binding we can also use the on- prefix, known as the canonical form:

<button on-click="onShow()" >Show</button>

Two-way Data-Binding

Angular gives us a very nice way to bind data and it is Two-way Data-Binding. Any change in value in view will also change in the typescript file.

Importantly for two-way binding, we need to import FormModule from @angular/forms in the app.module.ts file after importing FormModule then we are using ngModel directive in our template for binding the data.

[(ngModel)] = ”[property of your component]” like this in our template .

For example

app.module.ts file

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

app.component.html file

<h2>Two Way Data binding Example</h2>
<input type="text" [(ngModel)]="title" >

In the app.component.html file, I am binding the title. if we change the input text value it will reflect in the component typescript file and the title in the h2 tag also changes.

Output:

Github repo link

Angular Data-Binding Example

Conclusion

In conclusion,  we can say that understanding Angular’s data binding types is important. When building Angular applications, with this knowledge, you can properly utilize the data binding method most suitable for the task at hand. With property binding, you can do things such as toggle button functionality, set paths programmatically, and share data between components, hence, data-binding play an important role in everyday life of Angular developer.