Data Binding
Last updated
Was this helpful?
Last updated
Was this helpful?
Each form has a direction—to the DOM, from the DOM, or in both directions.
You often want to both display a data property and update that property when the user makes changes.
In two-way binding, a data property value flows to the input box from the component as with property binding. The user's changes also flow back to the component, resetting the property to the latest value, as with event binding.
Angular processes all data bindings once per JavaScript event cycle, from the root of the application component tree through all child components.
two-way binding = property binding + event binding
That ngModel
directive hides these onerous details behind its own ngModel
input and ngModelChange
output properties.
The [(ngModel)]
syntax can only set a data-bound property. If you need to do something more or something different, you can write the expanded form.
The following contrived example forces the input value to uppercase:
The [(x)]
syntax is easy to demonstrate when the element has a settable property called x
and a corresponding event named xChange
. Here's a SizerComponent that fits the pattern. It has a size value property and a companion sizeChange event:
The two-way binding syntax is really just syntactic sugar for a property binding and an event binding. Angular desugars the SizerComponent binding into this:
It would be convenient to use two-way binding with HTML form elements like <input>
and <select>
. However, no native HTML element follows the x
value and xChange
event pattern.
Fortunately, the Angular NgModel directive is a bridge that enables two-way binding to form elements.
Althoughis a valid Angular directive, it isn't available by default. It belongs to the optionaland you must opt-in to using it.