Angular - 2.17-Transmit and use data with event link
In the previous lesson we discovered event binding. Before moving on to two-way binding, there is one important extra detail to know about event binding: how to transmit and use the data carried by the event itself. Most DOM events do not only fire - they also send a payload, and Angular gives us a clean way to retrieve it inside the template.
Imagine that, above the "Create server" button, we now also have a label and a text input styled with the Bootstrap class form-control. We want the application to react to whatever the user types. The input element emits a native DOM input event on every keystroke, so we can listen to it with the event binding syntax: <input (input)="onUpdateServerName($event)">.
The $event reserved variable
$eventis a reserved name available inside the quotes of an event binding.- It exposes the event object emitted by the DOM (or by a custom event of a directive/component).
- You can pass it to a method as an argument or use it directly in any TypeScript expression between the quotes.
In the component, the handler now looks like onUpdateServerName(event: Event) { this.serverName = (event.target as HTMLInputElement).value; }. Each character typed triggers the event four times for "test" (one per key), and each time we read event.target.value to extract the current text of the input. A quick console.log(event) shows the full DOM payload: the type of event, the target element, and many other properties.
From there, the conclusion is straightforward: $event works for any DOM event (click, focus, keyup, submit, etc.) and also for custom events emitted by Angular components through EventEmitter. With property binding, event binding and $event in our toolbox we are ready for the next step - two-way binding via [(ngModel)], which fuses both directions into a single expression.