Back to all posts

Angular: Property Binding


In Angular, Property Binding is a one-way binding mechanism that binds the properties of DOM elements (like <input>, <img>, <div>, etc ) to variable or expressions in component class. This means that when the value in the component changes, the corresponding element property gets updated automatically.

Unlike Attribute Binding (which targets the HTML attributes directly), Property Binding targets the underlying DOM object properties. This distinction is important because not all attributes have corresponding DOM properties, and some attributes cannot be dynamically updated using standard property binding.

Syntax of property Binding

The syntax for Property Binding in Angular uses square brackets [ ] around the property name. Here’s a basic example:

<img [src]="imageUrl" alt="Dynamic Image">

Key Points:

  1. Property Binding uses square brackets [].
  2. It binds DOM properties, not HTML attributes.
  3. It works dynamically, so whenever the property value changes, the DOM element is updated automatically.

Basic Example of Property Binding

Let’s take a look at a simple example where we dynamically change the image source based on the component’s data.

1. Component Class (app.component.ts):

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  imageUrl = 'https://via.placeholder.com/150';
  newImageUrl = 'https://via.placeholder.com/200';
}

2. Template (app.component.html):

<div>
  <h2>Dynamic Image Binding Example</h2>
  <img [src]="imageUrl" alt="Placeholder Image">
  <button (click)="imageUrl = newImageUrl">Change Image</button>
</div>

Binding Attributes with attr Prefix

While property binding is great for most DOM properties, it doesn’t work for HTML attributes that don’t have corresponding DOM properties. For example, ARIA attributes (such as aria-label, aria-hidden, etc.) are attributes, not properties, so you can’t use regular property binding to bind them.

To bind such attributes, Angular provides a slight variation of the property binding syntax using the attr prefix.

Example: Binding ARIA Attributes

<div 
  role="progressbar" 
  [attr.aria-valuenow]="currentVal" 
  [attr.aria-valuemax]="maxVal">
</div>