AngularJS2 user input
Users click on a link, press the button or input text, the user interaction behavior will trigger DOM events.
In this chapter, we will learn how to use Angular event binding syntax to bind these events.
The following diagram illustrates the operation of the Gif instance:
Source code can be downloaded at the end of the article.
Is bound to a user input event
We can use Angular event binding mechanism to respond to any DOM events.
The following example binds the click event:
<button (click)="onClickMe()">点我!</button>
Equal sign on the left (click) to indicate the button's click event as a binding target. Right-hand side, quotes text is a template statement
The complete code is as follows:
app / click-me.component.ts file:
Get user input via the $ event objects
We can bind to all types of events.
Let's try to bind to the keyup event an input box, and the user input stuff echoed to the screen.
app / keyup.component.ts (v1) file:
The above code, we listen for an event and capture user input, Angular the event object into the $ event variable.
onKey component () method is used to extract user input, the value added to the property and then input values from the event object.
Get user input from a template reference variable
You can use a local variable to display user data template, templates, reference variables by prefixing the identifier with a pound sign (#) to achieve.
The following example demonstrates how to use a local template variables:
app / loop-back.component.ts file:
We <input>
on the element defines a named box
template reference variables. box
variable reference is the <input>
element itself, which means we can get input element value
value, and display it through interpolation expression in the <p>
tag.
We can use the template reference variable to modify the above instance keyup:
app / keyup.components.ts (v2) file:
Key event filtering (by key.enter)
We can press ENTER (enter) key only when the user only to get the value of the input box.
(Keyup) event handler statement hear every keystroke, we can filter keys, such as every $ event.keyCode, only press the Enter key to update property values.
Angular keyboard events can be filtered for us, by binding to the keyup.enter Angular pseudo event listeners Enter key events.
app / keyup.components.ts (v3):
blur (losing focus) events
Then we can use the blur (losing focus) event, update property values that can be the element loses focus.
The following examples while listening ENTER to input box loses focus events.
app / keyup.components.ts (v4):
As used herein, the source code can be downloaded in the following ways, and does not contain node_modules typings directory.