October 15, 2024

Angular 10 – Databinding

In this part, we would cover Databinding under the following topics:

  1. What is Databinding?
  2. One-way Databinding
    • Interpolation
    • Property Binding
    • Event Binding
  3. Two-way Databinding

 

1. What is Databinding?

Databinding in Angular is way of communicating between the DOM and the business logic. In order words, how does the data in the HTML page bind to the TypeScript code.

This is important because when you write TypeScript code, it is compiled into JavaScript and the final output is on a HTML template. Therefore, when something changes in the code, users should be able to see the output immediately. This is why we need databinding.

There are two type of databinding we’ll discuss here.

 

2. One-way databinding

This type of databinding is like a one-way communication. If the value in the TypeScript code changes, then the change is updated in the HTML element. But not vice versa. Put in another way, we can update the view from the model but you can’t update the model from the view.

Example of one-way databinding includes:

  • Interpolation
  • Event Binding
  • Property Binding

 

Interpolation {{…}}

This is simply a way to display dynamic data in the HTML page.

For example, if we have a string firstname in our ngOnInit() method as shown below

  ngOnInit(): void {
    this.firsname = 'Kindson The Genius';
  }

then we could use it in the HTML

{{firsname}}

This would render the text on the page.

 

Property Binding […]

This  is used  to set the property of a HTML element to a component property value. It uses the square brackets. In the example below, the disabled property of the button is set to the value of the isDisabled field in the TypeScript file. Similarly, the src property of the image is set to the value of the imgUrl variable.

<h1>Example of Property Binding</h1>
<img [src]="imgUrl">
<button [disabled]="isDisabled">You Cannot Click here</button>

 

Event Binding

This is used to bind an event for a DOM element. For example, button click event or textChanged event.  The example below show binding a button click event to a save() method.

<h1>Example of Event Bindin</h1> 
<button (click)="onSave()">Update</button>

 

3. Two-way databinding [(…)]

In case of two-way databinding, data is automatically synchronized between the model and the view. This is really interesting to see. Any changes made in the HTML is updated in the variable in the TypeScript code and vice versa. Two-way databinding is also known as ‘banana in the box’.

To achieve this, use the ngModel with an input elements like shown below:

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

See the video for the practical

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments