Loading...

Property Binding in Angular

In the last chapter, we learned about string interpolation, which helps achieve one-way data binding by passing data from the component class to its view template. In this lecture, we will discuss property binding.

Like string interpolation, property binding also enables one-way data binding, passing data from the component class to its view template. The key difference is:

  • String interpolation is used to display dynamic content inside HTML.
  • Property binding is used to bind an HTML element’s property to a value in the component class, allowing us to manipulate the DOM.

Syntax

Syntax

Property binding uses square brackets [ ] around the property:

<element [property]="expression"></element>
Here, the expression is evaluated in the component and assigned to the property of the element.

Component (TypeScript) - app.component.ts

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

            @Component({
                selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
                })
export class AppComponent {
  title = 'Angular Property Binding Example';
  imageUrl = 'https://angular.io/assets/images/logos/angular/angular.png';
  isDisabled = true;
}

Template (HTML) - app.component.html

<h1 [innerText]="title"></h1>

<!-- Property Binding with Image Source -->
<img [src]="imageUrl" width="100" height="100">

<!-- Property Binding with Button Disabled -->
<button [disabled]="isDisabled">Click Me</button>

How It Works

  • [innerText]="title" → Binds the title variable to the innerText of the <h1> tag.
  • [src]="imageUrl" → Dynamically sets the src of the <img> tag.
  • [disabled]="isDisabled" → The button is disabled based on the isDisabled variable.

Difference Between Property Binding & Interpolation ({{ }})

Feature Property Binding [ ] Interpolation {{ }}
Usage [property]="expression" {{ expression }}
Works with HTML attributes? ✅ Yes ❌ No (Only for text content)
Example <img [src]="imageUrl"> <img src="{{imageUrl}}">

Example where interpolation won’t work:

<!-- Interpolation will NOT work here -->
<button disabled="{{isDisabled}}">Click Me</button>

Because disabled is a property, it requires property binding:

<button [disabled]="isDisabled">Click Me</button>

Use Cases of Property Binding

  • Setting image sources dynamically:
  • <img [src]="userProfilePic">
  • Enabling/disabling buttons:
  • <button [disabled]="!isLoggedIn">Login</button>
  • Changing styles dynamically:
  • <div [style.color]="isError ? 'red' : 'green'">Status</div>
Note: In place of square bracket [ ] we can use bind keyword with property also like this.
<img bind-src="userProfilePic">
<button bind-disabled="!isLoggedIn">Login</button>
        

The above code will work same as square bracket

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!