Property Binding
Property binding is another one-way data binding technique in Angular that allows you to bind a property of a DOM element to a component’s property. This binding is achieved using square brackets [] in the HTML template.
Syntax of Property Binding:
<element [property]="expression"></element>
Features of Property Binding:
- Binding component properties to HTML element properties.
- Dynamic updates based on component property changes.
- Ideal for handling properties like disabled, src, href, etc.
Example of Property Binding:
Step 1: Create Angular Project
ng new property-binding-example
cd property-binding-example
Step 2: Create Component
ng generate component button
Folder Structure:
Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/compiler-cli": "^17.3.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
Code Example:
<!-- app.component.html -->
<app-button></app-button>
<!-- button.component.html -->
<button [disabled]="isDisabled"
(click)="toggleDisabled()">Toggle</button>
// button.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.css']
})
export class ButtonComponent {
isDisabled: boolean = true;
toggleDisabled() {
this.isDisabled = !this.isDisabled;
}
}
Run the Application using the following command
ng serve --open
Output:
Interpolation vs. Property Binding in Angular
Angular, a powerful front-end framework, offers various techniques to dynamically update and display data in your applications. Two commonly used methods for this purpose are interpolation and property binding.
In this article, we will learn about interpolation and property binding and also see the key differences between them.
Table of Content
- Interpolation
- Property Binding
- Difference between interpolation and property binding in Angular
- Summary