Angular Property Binding

In the previous article, we have learned about interpolation in Angular and how interpolation helps in displaying data dynamically. In this article, we’ll be learning about property binding and how it works with DOM elements.

What is Property Binding in Angular?

Property Binding refers to the technique of one-way data binding. Here we bind the property of the DOM element with a variable which we declared on the component.ts file.

Syntax

<input type="text" [value]='MyName'>

MyName is the variable with a string value “KARAN” declared in the component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  MyName="KARAN"
}

But these criteria can be achieved using HTML attributes, then why property binding?

Let’s look at some differences between Attributes and Property Binding.

AttributesProperty Binding
Attributes are defined by HTMLProperty Binding is defined by DOM.
Attributes can’t be changed once they are initialized.Property Binding can be changed.
Syntax:

<input type=”text” value=”KARAN”>

Syntax:

<input type=”text” [value]=’MyName’>

This might have cleared all your doubts about why property binding is used over attributes and why it’s more flexible.

No, not yet. You must be wondering why we’re not using interpolation in this case to achieve these criteria?

Okay, let’s clear that too.

Interpolation has the limitation that it can only take string values. But there are more HTML properties that take boolean values, and there it is stuck.

For example, if we want to enable or disable a button on certain conditions, this can’t be achieved with interpolation.

<input type="text" [disabled]="isDisable">

isDisable is defined in the component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  isDisable = true
}

Conclusion

We hope this article will clear all your doubts regarding property binding. It’s a very important topic, and you’ll be using it many times while developing apps using angular. In the upcoming articles, we’re gonna see class binding and style binding as well.

Read Next: Angular Property Binding

Leave a Reply

Your email address will not be published. Required fields are marked *