Property versus attribute
Take any DOM element API and you will find attributes, properties, functions, and events. While events and functions are self-explanatory, it is difficult to understand the difference between properties and attributes. In daily use, we use these words interchangeably, which does not help much either. Take, for example, this line of code:
<input type="text" value="Awesome Angular">
When the browser creates a DOM element (HTMLInputElement to be precise) for this input textbox, it uses the value attribute on input to set the initial state of the value property of input to Awesome Angular.
After this initialization, any changes to the value property of input do not reflect on the value attribute; the attribute always has Awesome Angular (unless set explicitly again). This can be confirmed by querying the input state.
Suppose we change the input data to Angular rocks! and query the input element state:
input.value // value property
The value property always returns the current input content, which is Angular rocks!. Whereas this DOM API function:
input.getAttribute('value') // value attribute
Returns the value attribute, and is always the Awesome Angular that was set initially.
The primary role of an element attribute is to initialize the state of the element when the corresponding DOM object is created.
There are a number of other nuances that add to this confusion. These include the following:
- Attribute and property synchronization is not consistent across properties. As we saw in the preceding example, changes to the value property on input do not affect the value attribute, but this is not true for all property-value pairs. The src property of an image element is a prime example of this; changes to property or attribute values are always kept in sync.
- It's surprising to learn that the mapping between attributes and properties is also not one-to-one. There are a number of properties that do not have any backing attribute (such as innerHTML), and there are also attributes that do not have a corresponding property defined on the DOM (such as colspan).
- Attribute and property mapping adds to this confusion too, as they do not follow a consistent pattern. An excellent example of this is available in the Angular developer's guide, which we are going to reproduce here verbatim:
The aim of this discussion is to make sure that we understand the difference between the properties and attributes of a DOM element. This new mental model will help us as we continue to explore the framework's property and attribute binding capabilities. Let's get back to our discussion on property binding.