Sub topic 5
Responding to Events with Event Binding
Interpolation and property binding send data from the component class to the DOM. Event binding sends signals the other way: when the user clicks, types, or presses a key, Angular calls your code. This chapter covers how event bindings are written, what you can put in them, how to read $event without fighting the type checker, and where they tend to go wrong.
This chapter assumes you know DOM events (click, input, keydown, bubbling, preventDefault()), TypeScript type assertions, and the property binding covered in the previous chapter.
The Syntax and What It Means
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-like',
template: `
<button (click)="like()">Like</button>
<p>{{ likes }} likes</p>
`,
})
export class LikeComponent {
likes = 0;
like() {
this.likes++;
}
}The parentheses mean "target to source". Square brackets on [disabled] mean "source to target". The name inside the parentheses is the DOM event name exactly as you would pass it to addEventListener: click, input, focusout, submit. Do not include the on prefix, so write (click), not (onclick).
Behind the scenes, the compiler generates a listener registration through Angular's renderer. When the event fires, Angular runs your statement in the component's context and then schedules change detection. That is why {{ likes }} updates without any manual refresh.
Template Statements Are Not Template Expressions
The right-hand side of a property binding is an expression. Angular evaluates it to get a value, and it should have no side effects. The right-hand side of an event binding is a statement. It exists to cause side effects. The grammar is related, but the rules differ.
| Feature | Expression `[x]="..."` / `{{ }}` | Statement `(e)="..."` | Column |
|---|---|---|---|
| Plain assignment `a = b` | Not allowed | Allowed | |
| Multiple parts separated by `;` | Not allowed | Allowed | |
| `$event` | Not available | Available | |
| Pipes `\ | ` | Allowed | Not allowed |
| `new`, `++`, `--`, `+=`, bitwise operators | Not allowed | Not allowed | |
| Globals such as `window`, `console`, `document` | Not accessible | Not accessible |
So these all work:
import { Component } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<button (click)="open = !open">Toggle</button>
<button (click)="open = false; closedCount = closedCount + 1">Close</button>
@if (open) {
<p>Panel content</p>
}
<p>Closed {{ closedCount }} times</p>
`,
})
export class PanelComponent {
open = false;
closedCount = 0;
}Note the closedCount = closedCount + 1. Writing closedCount++ is rejected by the template parser.
A statement can use the component's public and protected members, $event, and template-local names such as template reference variables and @for loop variables. It cannot use anything else. (click)="console.log(item)" fails because console is not on the component. If you need a global, expose it through a method.
Reading `$event`
Inside an event binding, $event holds whatever the event source emitted. For native DOM events it is the DOM event object. For component outputs it is the emitted value, which a later chapter covers.
The spine example reads text from an input:
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;
}
}Why the cast is needed
With strict template type checking enabled, which is the CLI default (strictTemplates: true), Angular types $event using the DOM's event map. (input) gives Event, (keydown) gives KeyboardEvent, and (click) gives a MouseEvent. The target of any of these is typed as EventTarget | null, and EventTarget has no value. So the tempting inline version fails to compile:
<input (input)="value = $event.target.value">
error NG2: Object is possibly 'null'. / Property 'value' does not exist on type 'EventTarget'.You have three reasonable fixes:
- Pass
$eventto a method and cast there, as above. This is the most common choice. - Pass only the value you need, using a template reference variable. The chapter on template reference variables covers this.
- Use
$any($event.target).value. This turns off checking for that expression. It works, but it hides real mistakes, so treat it as a last resort.
Use `target` or `currentTarget`, depending on what you mean
event.target is the element where the event started, and event.currentTarget is the element whose listener is running. For an <input> they are the same element. For (click) on a <li> containing a <span>, a click on the span makes target the span, not the list item. If you need the element you bound to, read currentTarget, or avoid DOM access completely by passing data into the statement: (click)="select(item)".
Key Event Filtering
Angular adds pseudo-events for keyboard handling. Instead of checking event.key yourself, you can name the key in the binding:
import { Component } from '@angular/core';
@Component({
selector: 'app-todo-entry',
template: `
<form (submit)="$event.preventDefault(); add()">
<input
[value]="draft"
(input)="draft = readValue($event)"
(keydown.escape)="draft = ''"
placeholder="New task">
<button type="submit">Add</button>
</form>
<ul>
@for (item of items; track $index) {
<li>{{ item }}</li>
}
</ul>
`,
})
export class TodoEntryComponent {
draft = '';
items: string[] = [];
readValue(event: Event): string {
return (event.target as HTMLInputElement).value;
}
add() {
const text = this.draft.trim();
if (text) {
this.items.push(text);
}
this.draft = '';
}
}Some details in this example:
(keydown.escape)fires only for the Escape key. You can combine modifiers:(keydown.shift.enter),(keyup.control.s),(keydown.alt.arrowup). The modifiers arealt,control,metaandshift, and Angular requires exactly those modifiers to be held.- Key names match
KeyboardEvent.key, lowercased:enter,escape,space,arrowdown. To match the physical key regardless of keyboard layout, use thecodeform:(keydown.code.keyw). - Pressing Enter in a single-field form already submits it, so the example does not need a
(keyup.enter)handler. The(submit)listener calls$event.preventDefault()to stop the browser from reloading the page. If you importFormsModule, you can use(ngSubmit)instead, which prevents the default for you.
The reset gotcha
The (input) binding does more than mirror the field into draft. Property binding compares the new value with the previously bound value, not with what is currently in the DOM. If you removed (input), draft would stay '' while the user typed. Then add() would set it to '' again, Angular would see no change, and the text box would never clear. Keeping the field updated on every input is what makes [value] reliable. Two-way binding, covered in the next chapters, packages up exactly this pattern.
Global and Host Listeners
Sometimes the event you care about is not on an element in your template. Angular accepts the window:, document: and body: prefixes, and the component's host metadata lets you listen on the component's own element:
import { Component } from '@angular/core';
@Component({
selector: 'app-shortcuts',
host: {
'(document:keydown.control.k)': 'openSearch($event)',
'(window:resize)': 'onResize()',
'(click)': 'clicks = clicks + 1',
},
template: `
@if (searchOpen) {
<p>Search is open</p>
}
<p>Window width: {{ width }}px, clicks on me: {{ clicks }}</p>
`,
})
export class ShortcutsComponent {
searchOpen = false;
width = window.innerWidth;
clicks = 0;
openSearch(event: Event) {
event.preventDefault();
this.searchOpen = true;
}
onResize() {
this.width = window.innerWidth;
}
}Angular removes these listeners when the component is destroyed, so you do not need manual cleanup like you would with addEventListener. The older @HostListener('window:resize') decorator does the same thing. The host object is the style the Angular team currently recommends.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Clicking does nothing, no error | `(click)="save"` reads the method without calling it | Write `(click)="save()"` |
| `Property 'value' does not exist on type 'EventTarget'` | Strict typing of `$event.target` | Cast in a method, or pass a reference variable's value |
| `Parser Error: Unexpected token '++'` | Increment operators are not allowed in statements | Use `x = x + 1` or a method |
| Page reloads on submit | Native form submission | `$event.preventDefault()` or `(ngSubmit)` with `FormsModule` |
| Parent's handler also fires | The event bubbles to an ancestor's listener | Call `event.stopPropagation()` in the child's handler |
| `(onclick)` never fires | Angular treats it as a custom event named `onclick` | Drop the `on` prefix |
The bubbling row matters for nested clickable elements such as a delete button inside a selectable row. Each element's listener runs, from the innermost outward, unless one of them stops propagation:
import { Component } from '@angular/core';
@Component({
selector: 'app-row',
template: `
<div (click)="selected = true" [class.selected]="selected">
Row
<button (click)="remove($event)">Delete</button>
</div>
<p>Selected: {{ selected }}, removed: {{ removed }}</p>
`,
})
export class RowComponent {
selected = false;
removed = false;
remove(event: MouseEvent) {
event.stopPropagation();
this.removed = true;
}
}Exercise
A template contains <input (keyup)="query = $event.target.value"> and fails to compile under strictTemplates. Explain why, and rewrite it so that the component's query field updates only when the user presses Enter, with correct typing and no use of $any.
Show answer
Under strict templates, $event for keyup is a KeyboardEvent, whose target is typed EventTarget | null. EventTarget has no value property, so the compiler reports an error. Rewrite it as <input (keyup.enter)="search($event)"> with the method search(event: Event) { this.query = (event.target as HTMLInputElement).value; }. The .enter filter makes Angular invoke the statement only for the Enter key, and the cast inside the method narrows the target to an input element.
Exercise
A card has (click)="open(card)" on its outer div and a nested favorite button with (click)="toggleFavorite(card)". Clicking the favorite button also opens the card. Why does this happen, and what is the smallest change that fixes it?
Show answer
The click event bubbles from the button up to the outer div, so both listeners run: first the button's, then the div's. Pass the event to the button handler and stop propagation there: (click)="toggleFavorite(card, $event)" with toggleFavorite(card: Card, event: MouseEvent) { event.stopPropagation(); ... }. Writing (click)="$event.stopPropagation(); toggleFavorite(card)" inline also works, but the method keeps the template simpler.
Exercise
Which of these event bindings are valid template statements? (a) (click)="count = count + 1" (b) (click)="count += 1" (c) (click)="reset(); log('done')" (d) (click)="name = (raw | uppercase)"
Show answer
(a) and (c) are valid. Statements allow plain assignment and multiple parts separated by semicolons, provided reset and log are component members. (b) is invalid because compound assignment operators like += are not supported. (d) is invalid because pipes are not allowed in template statements. Do the transformation in a component method instead.