Forms
Get User Input - $event
The example above casts the $event
as an any
type. That simplifies the code at a cost. There is no type information that could reveal properties of the event object and prevent silly mistakes.
The $event
is now a specific KeyboardEvent
. Not all elements have a value property so it casts target to an input element. The OnKey
method more clearly expresses what it expects from the template and how it interprets the event.
Passing $event is a dubious practicePassing the entire DOM event into the method: the component has too much awareness of the template details. It can't extract information without knowing more than it should about the HTML implementation.
That breaks the separation of concerns between the template (what the user sees) and the component (how the application processes user data).
==> Pass values, not elements
Get User Input - template reference variable (#)
The template is completely self contained. It doesn't bind to the component, and the component does nothing.
This won't work at all unless you bind to an event.
Angular updates the bindings (and therefore the screen) only if the app does something in response to asynchronous events, such as keystrokes.
This example code binds the keyup event to the number 0, the shortest template statement possible. While the statement does nothing useful, it satisfies Angular's requirement so that Angular will update the screen.
Here's a rewrite of the previous keyup example that uses a template reference variable to get the user's input.
A nice aspect of this approach is that the component gets clean data values from the view. It no longer requires knowledge of the $event
and its structure.
Key Event
keyup : hears every keystroke
keyup.enter : calls the event handler only when the user presses Enter
blur : when the current state of the input box is lost
Hearing multiple events is available.
Last updated
Was this helpful?