Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

The Angular event binding infrastructure

Angular event binding allows a component to communicate with its parent through events.

If we look back at the app implementation, what we have encountered thus far are the property/attribute bindings. Such bindings allow a component/element to take inputs from the outside world. The data flows into the component.

Event bindings are the reverse of property bindings. They allow a component/element to inform the outside world about any state change.

As we saw in the pause/resume implementation, event binding employs round brackets (()) to specify the target event:

<div id="pause-overlay" (click)="pauseResumeToggle()"> 

This attaches a click event handler to the div that invokes the expression pauseResumeToggle() when the div is clicked.

Like properties, there is a canonical form for events too. Instead of using round brackets, the on- prefix can be used: on-click="pauseResumeToggle()"

Angular supports all types of events. Events related to keyboard inputs, mouse movements, button clicks, and touches. The framework even allows us to define our own event for the components we create, such as:

<workout-runner (paused)= "stopAudio()"></workout-runner> 

It is expected that events have side effects; in other words, an event handler may change the state of the component, which in turn may trigger a chain reaction in which multiple components react to the state change and change their own state. This is unlike a property binding expression, which should be side-effect-free. Even in our implementation, clicking on the div element toggles the exercise run state.