{ "id": "guide/user-input", "title": "User input", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

User inputlink

\n
\n
Marked for archiving
\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.

\n

In the meantime, this topic might be helpful: Event binding.

\n

If you think this content should not be archived, please file a GitHub issue.

\n
\n

User 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.

\n

Run the .

\n

Binding to user input eventslink

\n

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.

\n

To bind to a DOM event, surround the DOM event name in parentheses and assign a quoted\ntemplate statement to it.

\n

The following example shows an event binding that implements a click handler:

\n\n<button (click)=\"onClickMe()\">Click me!</button>\n\n\n\n

The (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.

\n

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:

\n\n@Component({\n selector: 'app-click-me',\n template: `\n <button (click)=\"onClickMe()\">Click me!</button>\n {{clickMessage}}`\n})\nexport class ClickMeComponent {\n clickMessage = '';\n\n onClickMe() {\n this.clickMessage = 'You are my hero!';\n }\n}\n\n\n

When the user clicks the button, Angular calls the onClickMe method from ClickMeComponent.

\n

Get user input from the $event objectlink

\n

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.

\n

The following code listens to the keyup event and passes the entire event payload ($event) to the component event handler.

\n\ntemplate: `\n <input (keyup)=\"onKey($event)\">\n <p>{{values}}</p>\n`\n\n\n

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.

\n\nexport class KeyUpComponent_v1 {\n values = '';\n\n onKey(event: any) { // without type info\n this.values += event.target.value + ' | ';\n }\n}\n\n\n

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.

\n

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.

\n

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.

\n

Suppose the user enters the letters \"abc\", and then backspaces to remove them one by one.\nHere's what the UI displays:

\n\n a | ab | abc | ab | a | |\n\n
\n \"key\n
\n
\n

Alternatively, you could accumulate the individual keys themselves by substituting event.key\nfor event.target.value in which case the same user input would produce:

\n\n a | b | c | backspace | backspace | backspace |\n\n\n
\n\n

Type the $eventlink

\n

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.

\n

The following example rewrites the method with types:

\n\nexport class KeyUpComponent_v1 {\n values = '';\n\n\n onKey(event: KeyboardEvent) { // with type info\n this.values += (event.target as HTMLInputElement).value + ' | ';\n }\n}\n\n\n

The $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.

\n

Passing $event is a dubious practicelink

\n

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).

\n

The next section shows how to use template reference variables to address this problem.

\n

Get user input from a template reference variablelink

\n

There'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 (#).

\n

The following example uses a template reference variable\nto implement a keystroke loopback in a simple template.

\n\n@Component({\n selector: 'app-loop-back',\n template: `\n <input #box (keyup)=\"0\">\n <p>{{box.value}}</p>\n `\n})\nexport class LoopbackComponent { }\n\n\n

The 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.

\n

The template is completely self contained. It doesn't bind to the component,\nand the component does nothing.

\n

Type something in the input box, and watch the display update with each keystroke.

\n
\n \"loop\n
\n
\n

This won't work at all unless you bind to an event.

\n

Angular 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.

\n
\n

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.

\n\n@Component({\n selector: 'app-key-up2',\n template: `\n <input #box (keyup)=\"onKey(box.value)\">\n <p>{{values}}</p>\n `\n})\nexport class KeyUpComponent_v2 {\n values = '';\n onKey(value: string) {\n this.values += value + ' | ';\n }\n}\n\n\n

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

\n

Key event filtering (with key.enter)link

\n

The (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.

\n

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.

\n\n@Component({\n selector: 'app-key-up3',\n template: `\n <input #box (keyup.enter)=\"onEnter(box.value)\">\n <p>{{value}}</p>\n `\n})\nexport class KeyUpComponent_v3 {\n value = '';\n onEnter(value: string) { this.value = value; }\n}\n\n\n

Here's how it works.

\n
\n \"key\n
\n

On blurlink

\n

In 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.

\n

To fix this issue, listen to both the Enter key and the blur event.

\n\n@Component({\n selector: 'app-key-up4',\n template: `\n <input #box\n (keyup.enter)=\"update(box.value)\"\n (blur)=\"update(box.value)\">\n\n <p>{{value}}</p>\n `\n})\nexport class KeyUpComponent_v4 {\n value = '';\n update(value: string) { this.value = value; }\n}\n\n\n

Put it all togetherlink

\n

This page demonstrated several event binding techniques.

\n

Now, 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.

\n
\n \"Little\n
\n

Below is the \"Little Tour of Heroes\" component.

\n\n@Component({\n selector: 'app-little-tour',\n template: `\n <input #newHero\n (keyup.enter)=\"addHero(newHero.value)\"\n (blur)=\"addHero(newHero.value); newHero.value='' \">\n\n <button (click)=\"addHero(newHero.value)\">Add</button>\n\n <ul><li *ngFor=\"let hero of heroes\">{{hero}}</li></ul>\n `\n})\nexport class LittleTourComponent {\n heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];\n addHero(newHero: string) {\n if (newHero) {\n this.heroes.push(newHero);\n }\n }\n}\n\n\n

Observationslink

\n\n

Source codelink

\n

Following is all the code discussed in this page.

\n\n\n \nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'app-click-me',\n template: `\n <button (click)=\"onClickMe()\">Click me!</button>\n {{clickMessage}}`\n})\nexport class ClickMeComponent {\n clickMessage = '';\n\n onClickMe() {\n this.clickMessage = 'You are my hero!';\n }\n}\n\n\n\n\n \nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'app-key-up1',\n template: `\n <input (keyup)=\"onKey($event)\">\n <p>{{values}}</p>\n `\n})\nexport class KeyUpComponent_v1 {\n values = '';\n\n /*\n onKey(event: any) { // without type info\n this.values += event.target.value + ' | ';\n }\n */\n\n onKey(event: KeyboardEvent) { // with type info\n this.values += (event.target as HTMLInputElement).value + ' | ';\n }\n}\n\n//////////////////////////////////////////\n\n@Component({\n selector: 'app-key-up2',\n template: `\n <input #box (keyup)=\"onKey(box.value)\">\n <p>{{values}}</p>\n `\n})\nexport class KeyUpComponent_v2 {\n values = '';\n onKey(value: string) {\n this.values += value + ' | ';\n }\n}\n\n//////////////////////////////////////////\n\n@Component({\n selector: 'app-key-up3',\n template: `\n <input #box (keyup.enter)=\"onEnter(box.value)\">\n <p>{{value}}</p>\n `\n})\nexport class KeyUpComponent_v3 {\n value = '';\n onEnter(value: string) { this.value = value; }\n}\n\n//////////////////////////////////////////\n\n@Component({\n selector: 'app-key-up4',\n template: `\n <input #box\n (keyup.enter)=\"update(box.value)\"\n (blur)=\"update(box.value)\">\n\n <p>{{value}}</p>\n `\n})\nexport class KeyUpComponent_v4 {\n value = '';\n update(value: string) { this.value = value; }\n}\n\n\n\n\n \nimport { Component } from '@angular/core';\n@Component({\n selector: 'app-loop-back',\n template: `\n <input #box (keyup)=\"0\">\n <p>{{box.value}}</p>\n `\n})\nexport class LoopbackComponent { }\n\n\n\n\n \nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'app-little-tour',\n template: `\n <input #newHero\n (keyup.enter)=\"addHero(newHero.value)\"\n (blur)=\"addHero(newHero.value); newHero.value='' \">\n\n <button (click)=\"addHero(newHero.value)\">Add</button>\n\n <ul><li *ngFor=\"let hero of heroes\">{{hero}}</li></ul>\n `\n})\nexport class LittleTourComponent {\n heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];\n addHero(newHero: string) {\n if (newHero) {\n this.heroes.push(newHero);\n }\n }\n}\n\n\n\n\n\n

Angular also supports passive event listeners. For example, you can use the following steps to make the scroll event passive.

\n
    \n
  1. Create a file zone-flags.ts under src directory.
  2. \n
  3. Add the following line into this file.
  4. \n
\n\n(window as any)['__zone_symbol__PASSIVE_EVENTS'] = ['scroll'];\n\n
    \n
  1. In the src/polyfills.ts file, before importing zone.js, import the newly created zone-flags.
  2. \n
\n\nimport './zone-flags';\nimport 'zone.js'; // Included with Angular CLI.\n\n

After those steps, if you add event listeners for the scroll event, the listeners will be passive.

\n

Summarylink

\n

You have mastered the basic primitives for responding to user input and gestures.

\n

These 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.

\n\n \n
\n\n\n" }