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
SyntaxProperty binding uses square brackets [ ] around the property:
<element [property]="expression"></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 thetitle
variable to theinnerText
of the<h1>
tag.[src]="imageUrl"
→ Dynamically sets thesrc
of the<img>
tag.[disabled]="isDisabled"
→ The button is disabled based on theisDisabled
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:
- Enabling/disabling buttons:
- Changing styles dynamically:
<img [src]="userProfilePic">
<button [disabled]="!isLoggedIn">Login</button>
<div [style.color]="isError ? 'red' : 'green'">Status</div>
[ ]
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!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.