In this post we are going to learn property binding in angular . Before learning property binding in angular we should know the difference between HTML Attribute
and DOM property
Attribute and properties are not same .
Attribute:
- Attribute defined by HTML.
- Attribute initialized DOM property and they are done . Attribute value can not change once they are initialized .
Property:
- Property defined by DOM (Document Object Model).
- Property value can change
Example
Here in below example the input tag the initial value of the input element is value="initialValue"
, when the HTML is loaded in the browser and the DOM is prepared then DOM initialized a value property
for the input element.
Now when we are changing the value in the input filed from initialValue
to codelearningpoint
now the DOM property value is getting updated and the input value attribute still having the same value.
that is why in the below example after changing the value in input filed , in the chrome console when we are printing the attribute document.querySelector('input').getAttribute('value');
it's printing the initialValue
and when we are printing value property document.querySelector('input').value;
it's printing the updated value which is codelearningpoint
.
Example
<input type="text" value="initialValue">
So in angular property binding we are binding the HTML attributes but in actual we are binding DOM property.
src/app/app.component.html
<button [id]="btnId">Test</button>
src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
btnId= "testBtn"
}
In above example the button element is having id property and we are setting value to the id property dynamically by using property binding.
One questing can comes to your mind , can we use angular interpolation instead of using property binding ?
The answer is yes we can use but there are some limitation in angular interpolation.
Example
Interpolation
only works with string value , Suppose in a button and you want to disable and enable the button based on some condition. To disable a button we have disabled
property and we can not set string
value to the disabled property, it only works with boolean
.
In such case we need to use property binding.
src/app/app.component.html
<button [id]="btnId" disabled='isDisabled'>Test</button>
src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
btnId= "testBtn"
isDisabled=true;
}
So if you are binding any property then it's better to use property binding instead of of using interpolation.
I hope this article is helpful for you , i am very glad to help you thanks for reading