Property Binding (DOM Property)

What is Property Binding?

When we can assign an attribute value with a property is called a property binding, Like if we set a property myId with the value “testId” in the component class and if we wish to make the value of an attribute of HTML of the template then we have to enclose the attribute with a third bracket and then after the equal sign has to give the property name inside the quotation.

Example:

HTML Template: <input [id]=”myId” type=”text” value=”sample value” />

Class property: public myId = “testId”;

* Note: We can also use interpolation to bind a property with an HTML element.

for that does not need to enclose the attribute with the third bracket. instead of that, we have to close the property name with a double curly bracket like the code below.

<input type=”text” id=”{{ myId }}” value=”sample value” />

For both cases, the property name myId will be replaced with the value of the property “testId”.

We have to note some more points also and they are described below:

  • Attributes and properties are not the same
  • Attributes are defined by the HTML
  • Properties are defined by the Document object module (DOM)
  • Attributes initialized DOM properties and the tusk is done, and the Attribute value can not be changed once they are initialized. but property values can be changed, however.

So why we do need property binding?

As there have some limitations, as it’s working with only string values, there are some properties with boolean type and in this case, interpolation will not going to work. So in the case of attribute values, we should use property binding instead of interpolation.

Example:

in case of interpolation: <input type=”text” disabled=”{{ false }}” />

in case of property binding: <input type=”text” [disabled]=”false” />

In the case of interpolation, the input will remain disabled, but in the case of property binding it will the input type is going to work, as the value is boolean type then the interpolation is not going to work there.

Why is Property binding?

  • Instead of a square bracket, we can use bind: Example: <input bind-disabled=”false” type=”text” />
  • As we have already discussed we can use the square bracket to bind a property.
  • And also told that we can use interpolation to bind a property, that is a property value that will be self on the component classes and will be bound with the attribute value.

Note: We can say that if we need to bind property using interpolation then the value has to be in the string. If the value is in boolean or in number then interpolation is not going to work.

So in the case of angular application it’s a good practice to use property binding instead of interpolation.

Share The Post On -