Each component can have inputs and outputs. By creating bindings, it is possible to feed data into other components. Additionally, through their outputs, components can provide information to the outside world. Components that make use of other components can bind to their outputs in order to be able to react to the events emitted by them.
Here's a useful diagram from the official documentation that gives a summary of the binding possibilities and the associated syntax:
As you can see, we can define the following:
- One-way bindings use the following:
- Interpolation/expressions: {{ expression }}
- Property bindings: [property]="..."
- Event bindings: (event)="...", associated with template statements
- Two-way bindings use the so-called banana-in-a-box syntax: [(ng-model)]="...".
These bindings can be grouped into multiple categories depending on the direction of the data flow, as proposed in the official Angular documentation:
- From data source to view (that is, from components to elements) using expressions and property bindings
- From view to data source (that is, from elements to components) using event bindings
- From view to data source to view, using two-way bindings
Using property bindings, you can set properties of view elements, directives, and components. Note that interpolation is usually a nicer alternative, syntax-and readability-wise, to property bindings.
In practice, when you're defining data bindings, they only refer to properties and events of the target objects; HTML attributes don't remain. Stated differently, the target of a data binding is something in the DOM.
It is important to understand the difference between HTML attributes and DOM properties in order to grasp how Angular bindings work. Attributes are defined through HTML, but properties are defined at the DOM level.
Finally, attributes initialize DOM properties. While property values can change after initialization, attribute values cannot. With Angular, attributes only initialize the element/directive state. You can refer to the following section in the Angular documentation to learn more: https://angular.io/guide/template-syntax#html-attribute-vs-dom-property.
When you define event bindings, you associate specific events with template statements that are executed as a reaction to those events. Of course, events have side-effects. For example, you can update the state of your application and perform subsequent actions if needed. We'll make use of event bindings and learn a bit more about them later on in this chapter.
Let's delve more deeply into components.