Sub topic 5
Responding to Events with Event Binding
This chapter assumes you know how JavaScript DOM events work, can read TypeScript classes, and have used interpolation and property binding from earlier chapters. Those bindings move data from the component into the template. Event binding moves information the other way: from the DOM back into the component.
The Syntax
An event binding puts the event name in parentheses on the left and a template statement on the right:
import { Component } from '@angular/core';
@Component({
selector: 'app-echo',
template: `
<input (input)="onInput($event)">
<p>You typed: {{ value }}</p>
`,
})
export class EchoComponent {
value = '';
onInput(event: Event) {
this.value = (event.target as HTMLInputElement).value;
}
}Angular attaches a listener for the input event to the <input> element. Each time the event fires, Angular runs onInput($event) in the context of the component instance. The method updates value, and the interpolation in the paragraph shows the new text.
The right-hand side is a template statement, not a template expression. A statement may have side effects, such as calling a method or assigning a field ((click)="count = count + 1"). It can also chain several actions with ;. Statements still can't use new, increment operators like ++, or global objects such as window and console.
What `$event` Contains
$event is the payload of the event. For native DOM events it is the browser's event object: a MouseEvent for click, a KeyboardEvent for keyup, and an InputEvent for input. For component outputs, which a later chapter covers, $event is whatever value the child emits.
TypeScript types event.target as EventTarget | null, which has no value property. That is why the example casts it to HTMLInputElement. A common alternative is to pass only what the method needs:
import { Component } from '@angular/core';
@Component({
selector: 'app-search',
template: `
<input (keyup.enter)="search($any($event.target).value)">
<button (click)="clear()">Clear</button>
<p>Last search: {{ query || '(none)' }}</p>
`,
})
export class SearchComponent {
query = '';
search(term: string) {
this.query = term.trim();
}
clear() {
this.query = '';
}
}$any() turns off type checking for one expression. It is convenient in templates, but it hides mistakes. Prefer typed handlers when the logic is more than a single line.
Key Event Filtering
(keyup.enter) is a pseudo-event. Angular only calls the handler when the key is Enter, so you don't need if (event.key === 'Enter') in your method. You can combine modifiers, as in (keydown.shift.tab) or (keyup.control.s).
What Happens After the Handler Runs
Angular schedules change detection after a bound event handler runs, so state you change in the handler shows up in the view. A later chapter explains this process in detail.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `(click)="save"` without `()` | Nothing happens | Call it: `(click)="save()"` |
| `onclick="save()"` | `save is not defined` | Use Angular syntax: `(click)` |
| `$event.target.value` in strict mode | Type error on `value` | Cast in the handler or use `$any()` |
| Misspelled event like `(onClick)` | Silently never fires | Use the DOM event name: `click` |
Exercises
Exercise
Write a template line where a button increments a component field count on each click, without a method.
Show answer
<button (click)="count = count + 1">+1</button>. An assignment is allowed in a template statement, but count++ is not, because statements don't support increment operators.
Exercise
An input uses (keyup)="submit()", but submit should run only when the user presses Enter. What is the smallest change?
Show answer
Change the binding to (keyup.enter)="submit()". Angular then filters out every key except Enter.
Exercise
In a (click) binding on a button, what type is $event, and in a binding on a component's custom output, what is it?
Show answer
On a button it is the browser's MouseEvent. On a component output it is whatever value the child passes to emit().