Property Binding
Deep dive into property binding — bind DOM properties, HTML attributes, classes, and styles dynamically.
Property Binding
Property binding lets you set DOM properties dynamically from your component data. It's one-way — data flows from the component to the template.
Basic Property Binding
// component
export class ProductComponent {
productName = 'Angular Handbook';
imageUrl = '/assets/book.jpg';
isAvailable = true;
quantity = 0;
}
// template
<h2 [innerText]="productName"></h2>
<img [src]="imageUrl" [alt]="productName">
<button [disabled]="!isAvailable">Buy Now</button>
<input [value]="quantity" type="number">
Property vs Attribute
HTML attributes and DOM properties are not the same thing:
| HTML Attribute | DOM Property |
|---|---|
| Initial value only | Current value |
value="hello" | element.value = "hello" |
| Doesn't change after init | Changes with user interaction |
<!-- Angular binds to DOM PROPERTIES, not HTML attributes: -->
<input [value]="name"> <!-- Binds to the .value property -->
<!-- To bind to an HTML attribute, use attr. prefix: -->
<td [attr.colspan]="columnSpan"></td>
<div [attr.role]="ariaRole"></div>
<div [attr.aria-label]="label"></div>
Class Binding
<!-- Toggle a single class -->
<div [class.active]="isActive">Tab</div>
<div [class.error]="hasError">Message</div>
<div [class.hidden]="!isVisible">Content</div>
<!-- Multiple classes with ngClass -->
<div [ngClass]="{
'active': isActive,
'disabled': isDisabled,
'large': size === 'lg'
}">Element</div>
<!-- Array of classes -->
<div [ngClass]="['card', 'shadow', theme]">Card</div>
Style Binding
<!-- Single style property -->
<div [style.color]="textColor">Colored text</div>
<div [style.font-size.px]="fontSize">Sized text</div>
<div [style.width.%]="widthPercent">Sized div</div>
<div [style.background-color]="bgColor">Background</div>
<!-- Multiple styles with ngStyle -->
<div [ngStyle]="{
'color': isError ? 'red' : 'green',
'font-weight': isBold ? 'bold' : 'normal',
'font-size': fontSize + 'px'
}">Styled text</div>
Binding to Component Properties
// component
export class AlertComponent {
alertType = 'warning';
message = 'Please check your input.';
get alertClass(): string {
return `alert alert-${this.alertType}`;
}
get alertIcon(): string {
const icons: Record<string, string> = {
success: '✅', warning: '⚠️', error: '❌', info: 'ℹ️'
};
return icons[this.alertType] || 'ℹ️';
}
}
// template
<div [class]="alertClass">
<span>{{ alertIcon }}</span>
<p>{{ message }}</p>
</div>
Key Takeaways
- Property binding uses
[property]="expression"syntax - Angular binds to DOM properties, not HTML attributes
- Use
[attr.name]to bind to HTML attributes (colspan, aria, data-*) [class.name]toggles a CSS class,[ngClass]handles multiple classes[style.prop]sets one style,[ngStyle]sets multiple styles- Property binding is one-way: component → template