{ "id": "guide/user-input", "title": "User input", "contents": "\n\n\n
To ensure that you have the best experience possible, this topic is marked for archiving until we determine\nthat it clearly conveys the most accurate information possible.
\nIn the meantime, this topic might be helpful: Event binding.
\nIf you think this content should not be archived, please file a GitHub issue.
\nUser actions such as clicking a link, pushing a button, and entering\ntext raise DOM events.\nThis page explains how to bind those events to component event handlers using the Angular\nevent binding syntax.
\nRun the
You can use Angular event bindings\nto respond to any DOM event.\nMany DOM events are triggered by user input. Binding to these events provides a way to\nget input from the user.
\nTo bind to a DOM event, surround the DOM event name in parentheses and assign a quoted\ntemplate statement to it.
\nThe following example shows an event binding that implements a click handler:
\nThe (click)
to the left of the equals sign identifies the button's click event as the target of the binding.\nThe text in quotes to the right of the equals sign\nis the template statement, which responds\nto the click event by calling the component's onClickMe
method.
When writing a binding, be aware of a template statement's execution context.\nThe identifiers in a template statement belong to a specific context object,\nusually the Angular component controlling the template.\nThe example above shows a single line of HTML, but that HTML belongs to a larger component:
\nWhen the user clicks the button, Angular calls the onClickMe
method from ClickMeComponent
.
DOM events carry a payload of information that may be useful to the component.\nThis section shows how to bind to the keyup
event of an input box to get the user's input after each keystroke.
The following code listens to the keyup
event and passes the entire event payload ($event
) to the component event handler.
When a user presses and releases a key, the keyup
event occurs, and Angular provides a corresponding\nDOM event object in the $event
variable which this code passes as a parameter to the component's onKey()
method.
The properties of an $event
object vary depending on the type of DOM event. For example,\na mouse event includes different information than an input box editing event.
All standard DOM event objects\nhave a target
property, a reference to the element that raised the event.\nIn this case, target
refers to the <input>
element and\nevent.target.value
returns the current contents of that element.
After each call, the onKey()
method appends the contents of the input box value to the list\nin the component's values
property, followed by a separator character (|).\nThe interpolation\ndisplays the accumulating input box changes from the values
property.
Suppose the user enters the letters \"abc\", and then backspaces to remove them one by one.\nHere's what the UI displays:
\nAlternatively, you could accumulate the individual keys themselves by substituting event.key
\nfor event.target.value
in which case the same user input would produce:
The example above casts the $event
as an any
type.\nThat simplifies the code at a cost.\nThere is no type information\nthat could reveal properties of the event object and prevent silly mistakes.
The following example rewrites the method with types:
\nThe $event
is now a specific KeyboardEvent
.\nNot all elements have a value
property so it casts target
to an input element.\nThe OnKey
method more clearly expresses what it expects from the template and how it interprets the event.
Typing the event object reveals a significant objection to passing the entire DOM event into the method:\nthe component has too much awareness of the template details.\nIt can't extract information without knowing more than it should about the HTML implementation.\nThat breaks the separation of concerns between the template (what the user sees)\nand the component (how the application processes user data).
\nThe next section shows how to use template reference variables to address this problem.
\nThere's another way to get the user data: use Angular\ntemplate reference variables.\nThese variables provide direct access to an element from within the template.\nTo declare a template reference variable, precede an identifier with a hash (or pound) character (#).
\nThe following example uses a template reference variable\nto implement a keystroke loopback in a simple template.
\nThe template reference variable named box
, declared on the <input>
element,\nrefers to the <input>
element itself.\nThe code uses the box
variable to get the input element's value
and display it\nwith interpolation between <p>
tags.
The template is completely self contained. It doesn't bind to the component,\nand the component does nothing.
\nType something in the input box, and watch the display update with each keystroke.
\nThis won't work at all unless you bind to an event.
\nAngular updates the bindings (and therefore the screen)\nonly if the app does something in response to asynchronous events, such as keystrokes.\nThis example code binds the keyup
event\nto the number 0, the shortest template statement possible.\nWhile the statement does nothing useful,\nit satisfies Angular's requirement so that Angular will update the screen.
It's easier to get to the input box with the template reference\nvariable than to go through the $event
object. Here's a rewrite of the previous\nkeyup
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.\nIt no longer requires knowledge of the $event
and its structure.\n
key.enter
)linkThe (keyup)
event handler hears every keystroke.\nSometimes only the Enter key matters, because it signals that the user has finished typing.\nOne way to reduce the noise would be to examine every $event.keyCode
and take action only when the key is Enter.
There's an easier way: bind to Angular's keyup.enter
pseudo-event.\nThen Angular calls the event handler only when the user presses Enter.
Here's how it works.
\nIn the previous example, the current state of the input box\nis lost if the user mouses away and clicks elsewhere on the page\nwithout first pressing Enter.\nThe component's value
property is updated only when the user presses Enter.
To fix this issue, listen to both the Enter key and the blur event.
\nThis page demonstrated several event binding techniques.
\nNow, put it all together in a micro-app\nthat can display a list of heroes and add new heroes to the list.\nThe user can add a hero by typing the hero's name in the input box and\nclicking Add.
\nBelow is the \"Little Tour of Heroes\" component.
\nUse template variables to refer to elements —\nThe newHero
template variable refers to the <input>
element.\nYou can reference newHero
from any sibling or child of the <input>
element.
Pass values, not elements —\nInstead of passing the newHero
into the component's addHero
method,\nget the input box value and pass that to addHero
.
Keep template statements simple —\nThe (blur)
event is bound to two JavaScript statements.\nThe first statement calls addHero
. The second statement, newHero.value=''
,\nclears the input box after a new hero is added to the list.
Following is all the code discussed in this page.
\nAngular also supports passive event listeners. For example, you can use the following steps to make the scroll event passive.
\nzone-flags.ts
under src
directory.src/polyfills.ts
file, before importing zone.js, import the newly created zone-flags
.After those steps, if you add event listeners for the scroll
event, the listeners will be passive
.
You have mastered the basic primitives for responding to user input and gestures.
\nThese techniques are useful for small-scale demonstrations, but they\nquickly become verbose and clumsy when handling large amounts of user input.\nTwo-way data binding is a more elegant and compact way to move\nvalues between data entry fields and model properties.\nThe Forms
page explains how to write\ntwo-way bindings with NgModel
.