9. Data Binding
Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to read as any experienced jQuery programmer can attest.
Angular supportsdata binding, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides.
As the diagram shows, there are four forms of data binding syntax. Each form has a direction - to the DOM, from the DOM, or in both directions.
TheHeroListComponent example template has three forms:
<li>{{hero.name}}</li>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
<li (click)="selectHero(hero)"></li>
- The
{{hero.name}}
interpolation displays the component'shero.name
property value within the<li>
element. - The
[hero]
property binding passes the value ofselectedHero
from the parentHeroListComponent
to thehero
property of the childHeroDetailComponent
. - The(click) event binding calls the component's
selectHero
method when the user clicks a hero's name.
Two-way data binding is an important fourth form that combines property and event binding in a single notation, using the ngModel directive.
Here's an example from theHeroDetailComponenttemplate:
<input [(ngModel)]="hero.name">
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.
Data binding plays an important role in communication between a template and its component.
Data binding is also important for communication between parent and child components.