What is Property Binding - Interpolation vs Property Binding
What is Property Binding?
Property Binding is used to bind component data to HTML element properties.
Definitions:
- Property Binding binds component data to DOM elements.
- Property Binding binds component data to HTML element properties.
Property Binding Syntax
Property Binding uses square brackets [ ].
Example:
<button [disabled]="btnDisable">Click Me</button>
disabled→ HTML element propertybtnDisable→ data coming from the TypeScript component
Why Property Binding is Needed?
Some HTML properties (like disabled, readonly, src) work with boolean or dynamic values.
Interpolation treats values as string, not actual boolean values.
Example 1: Button Disable (Interpolation vs Property Binding)
Using Interpolation (Wrong for boolean properties)
<button disabled="{{btnDisable}}">Click Me</button>
- Even if
btnDisableisfalse, the button remains disabled. - Reason: Interpolation treats the value as a string.
Using Property Binding (Correct)
<button [disabled]="btnDisable">Click Me</button>
true→ button disabledfalse→ button enabled
Toggle Button Example
HTML
<button (click)="toggle()">Toggle</button>
TypeScript
toggle(){
this.btnDisable = !this.btnDisable;
}
- Property Binding button toggles correctly
- Interpolation button does not respond properly
Example 2: Input Readonly
Using Interpolation
<input type="text" readonly="{{inputReadonly}}">
- Even when value is
false, input remains readonly
Using Property Binding
<input type="text" [readonly]="inputReadonly">
true→ readonlyfalse→ editable
Important Point from Video
Many HTML properties do not work properly with boolean values when using interpolation.
In such cases, Property Binding must be used.
Example 3: Image Source
Using Interpolation (Works but not recommended)
<img src="{{url}}" alt="">
Recommended: Property Binding
<img [src]="url" alt="">
srcis an HTML property- Property Binding is the recommended approach
When to Use Interpolation?
Use Interpolation when:
- Displaying normal text
- Showing data inside tags like
h1,p,span - Writing expressions inside HTML content
- One-way binding from component to view
Example:
<h1>{{title}}</h1>
When to Use Property Binding?
Use Property Binding when:
- Binding data to HTML element properties
- Working with boolean values
- Working with dynamic values
- Binding objects or URLs
- Binding to DOM properties like:
disabledreadonlysrcvalue