w3resource

User Input

User actions such as clicking a link, pushing a button, and entering text are all DOM events. In this tutorial, we will explore how to bind those events to component event handlers using the Angular event binding syntax.

Binding to user input events

You can use Angular event bindings to respond to any DOM event. Many DOM events are triggered by user input. Binding to these events provides a way to get input from the user.

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

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

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

The `(click)` to the left of the equals sign identifies the button's click event as the target of the binding. The text in quotes to the right of the equals sign is the template statement, which response to the click event by calling the component's `onClickMe` method.

When writing a binding, be aware of a template statement's execution context. The identifiers in a template statement belong to a specific context object, usually the Angular component controlling the template.

The example below illustrates binding to user input events

TypeScript Code:

@Component({
  selector: 'app-click-me',
  template: `
    <button (click)="onClickMe()">Click me!</button>
    {{clickMessage}}`
})
export class ClickMeComponent {
  clickMessage = '';

  onClickMe() {
    this.clickMessage = 'You are my hero!';
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen Binding to user input events by w3resource (@w3resource) on CodePen.


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

Get user input from the $event object

DOM events carry a payload of information that may be useful to the component. This 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.

TypeScript Code:


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

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen Get user input from the $event object by w3resource (@w3resource) on CodePen.


When a user presses and releases a key, the keyup event occurs, and Angular provides a corresponding DOM event object in the $event variable which this code passes as a parameter to the component's onKey() method.

TypeScript Code:

export class KeyUpComponent_v1 {
  values = '';

  onKey(event: any) {
    this.values += event.target.value + ' | ';
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen Get user input from the $event object 2 by w3resource (@w3resource) on CodePen.


The properties of a $event object vary depending on the type of DOM event. For example, a mouse event includes different information than an input box editing event.

All standard DOM event objects have a target property, a reference to the element that raised the event.

In this case, target refers to the <input> element and event.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 in the component's values property, followed by a separator character (|). The interpolation displays the accumulating input box changes from the values property.

Alternatively, you could accumulate the individual keys themselves by substituting event.key for event.target.value

Get user input from a template reference variable

There's another way to get the user data: use Angular template reference variables. These variables provide direct access to an element from within the template. To declare a template reference variable, precede an identifier with a hash (or pound) character (#).

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

TypeScript Code:

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

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen Get user input from a template reference variable by w3resource (@w3resource) on CodePen.


The template reference variable named `box`, declared on the `<input>` element, refers to the `<input>` element itself. The code uses the `box` variable to get the input element's `value` and display it with interpolation between `<p>` tags.

It's easier to get to the input box with the template reference variable than to go through the `$event` object. Here's a rewrite of the previous keyup example that uses a template reference variable to get the user's input.

TypeScript Code:

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

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen rewrite of template reference variable to get the user's input. by w3resource (@w3resource) on CodePen.


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 filtering (with key.enter)

The (keyup) event handler hears every keystroke. Sometimes only the Enter key matters, because it signals that the user has finished typing. One way to reduce the noise would be to examine every $event.keyCode and take action only when the key is Enter.

This could easily be done by using the Angular's keyup.enter pseudo-event. Then Angular calls the event handler only when the user presses Enter.

TypeScript Code:

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

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen Key event filtering (with key.enter) by w3resource (@w3resource) on CodePen.


On blur

In the previous example, the current state of the input box is lost if the user moves away and clicks elsewhere on the page without first pressing Enter. The 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.

TypeScript Code:

Component({
  selector: 'app-key-up4',
  template: `
    <input #box
      (keyup.enter)="update(box.value)"
      (blur)="update(box.value)">

    <p>{{value}} </p>
  `
})
export class KeyUpComponent_v4 {
  value = '';
  update(value: string) {this.value = value;}
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen On blur by w3resource (@w3resource) on CodePen.


Previous: Introduction to components
Next: Introduction to modules



Follow us on Facebook and Twitter for latest update.