Learn data binding types in Angular with examples
In this post, I’ll explain all of the data binding types in Angular with examples.
As developers we can push values to and pull values from HTML so that we can easily manage what end-users see within application. Angular as a framework is smart enough to handle such tasks and all we need to care about is declaring bindings as per requirements.
In Angular, binding types can be grouped into three categories and each type works with different direction of data flow from:
- Source to view
- View to source
- Two way sequence: view to source to view
A good way to summarise the data direction, syntax to use for the type can be seen in the table below:
from data source
to view target
from view target
to data source
Note that except Interpolation type, all other types have a target name to the left of the equal sign, either surrounded by punctuation (
()) or preceded by a prefix (
bindon-). Here, the target name is the name of a property.
Also, the target name is not an attribute of element. It looks like an attribute but it is actually a property of DOM element or component or directive.
HTML attribute vs. DOM property
From Angular docs: Attributes initialize DOM properties and then they are done. Property values can change; attribute values can’t. The HTML attribute and the DOM property are not the same thing, even when they have the same name.
Example to understand this concept:
When the browser renders
<input type="text" value="Bob">, it creates a corresponding DOM node with a value property initialized to “Bob”.
When the user enters “Sally” into the input box, the DOM element value property becomes “Sally”. But the HTML value attribute remains unchanged as you discover if you ask the input element about that attribute:
input.getAttribute('value') returns “Bob”.
The HTML attribute value specifies the initial value; the DOM value property is the current value.
I hope this post properly explains the data binding types in Angular with examples. If you would like to learn more about Angular then please checkout my other posts.