Sub topic 6
Responding to User Events
This chapter assumes you already know how to write a standalone component, display values with interpolation, read signals in a template, and bind DOM properties with [property]. You should also know how browser events work in general: the event object, target, bubbling, and preventDefault().
Property binding sends data from the class to the DOM. Event binding goes the other way. When something happens in the DOM, such as a click, a keystroke, or a form submit, Angular runs a statement you wrote in the template, and that statement usually calls a method on your class.
The Event Binding Syntax
Event binding puts the event name in parentheses on the left side of the attribute and a template statement on the right:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-like-button',
template: `
<button (click)="like()">Like</button>
<p>{{ likes() }} likes</p>
`
})
export class LikeButtonComponent {
likes = signal(0);
like() {
this.likes.update(n => n + 1);
}
}The name in parentheses is the DOM event name exactly as you would pass it to addEventListener: click, input, change, keydown, submit, focus, blur. It has no on prefix. If you write (onclick), Angular registers a listener for an event called onclick. That event never fires, and you get no error.
Behind the scenes, Angular calls addEventListener on the element when it creates the view and removes the listener when the view is destroyed. You never clean up template listeners yourself.
Template Statements Versus Template Expressions
The right side of a property binding is an expression: it should be cheap and free of side effects. The right side of an event binding is a statement, and side effects are its whole purpose. Statements follow slightly different rules:
- Assignment with
=is allowed:(click)="isOpen = false". - You can chain several statements with
;:(click)="save(); close()". - The context is the component instance, so names refer to class members. Global objects like
window,console, ordocumentare not reachable. - The increment and decrement operators (
++,--) are not allowed, and neither arenewor pipes.
Keep statements short. Once a statement does more than call one method or assign one value, move the logic into a class method, where you can test it and the type checker can check it fully.
Reading Event Data with $event
Inside an event binding, the special name $event holds the native event object, which is the same object addEventListener would pass to your callback. For DOM events this is a MouseEvent, KeyboardEvent, InputEvent, and so on.
The most common use is reading the current value of an input:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-name-field',
template: `
<input [value]="name()" (input)="onInput($event)" placeholder="Your name" />
<p>Hello, {{ name() || 'stranger' }}!</p>
`
})
export class NameFieldComponent {
name = signal('');
onInput(event: Event) {
const input = event.target as HTMLInputElement;
this.name.set(input.value);
}
}The typing gotcha with `$event.target`
Under strict template type checking, which new projects enable by default, $event.target has the type EventTarget | null. That type has no value property, so (input)="name.set($event.target.value)" fails to compile. Templates do not support TypeScript's as casts, which leaves you three options:
| Approach | Example | Trade-off |
|---|---|---|
| Pass `$event` to a method and cast there | `(input)="onInput($event)"` | Fully typed. Recommended. |
| Use the `$any()` template helper | `(input)="name.set($any($event.target).value)"` | Short, but turns off type checking for that expression |
| Read the element through a template reference variable | `#box` then `(input)="name.set(box.value)"` | Clean and typed. Covered in a later chapter. |
Passing $event to a method keeps the template simple and puts the cast in one visible place.
Key Event Filtering
Angular adds pseudo-events for keyboard handling. Append a key name to keydown or keyup, and the handler runs only for that key:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-quick-note',
template: `
<input
[value]="draft()"
(input)="onInput($event)"
(keydown.enter)="save()"
(keydown.escape)="draft.set('')"
(keydown.shift.enter)="save(); draft.set('')"
placeholder="Type a note, press Enter" />
<button (click)="save()" [disabled]="!draft()">Save</button>
<p>Saved notes: {{ count() }}</p>
<p>Last note: {{ lastNote() }}</p>
`
})
export class QuickNoteComponent {
draft = signal('');
lastNote = signal('(none)');
count = signal(0);
onInput(event: Event) {
this.draft.set((event.target as HTMLInputElement).value);
}
save() {
const text = this.draft().trim();
if (!text) return;
this.lastNote.set(text);
this.count.update(n => n + 1);
}
}Common filters:
| Binding | Fires when |
|---|---|
| `(keydown.enter)` | Enter is pressed |
| `(keydown.escape)` | Escape is pressed |
| `(keydown.space)` | The space bar is pressed |
| `(keydown.arrowdown)` | The down arrow is pressed |
| `(keydown.shift.enter)` | Shift and Enter are pressed together |
| `(keydown.control.s)` | Ctrl and S are pressed together |
Modifiers (shift, control, alt, meta) must match exactly. (keydown.enter) does not fire for Shift+Enter, because Shift is an extra modifier. That makes it easy to support "Enter saves, Shift+Enter does something else" on the same element.
The key names come from KeyboardEvent.key, so they follow the user's keyboard layout. If you need the physical key position no matter the layout, Angular also accepts the code form, for example (keydown.code.keyw).
What Happens After a Handler Runs
An event handler is one of the main triggers for change detection. After your statement finishes, Angular checks the component's template and updates any bindings whose values changed.
Because the handler marks the component for checking, events update the view even under OnPush components. A later chapter covers change detection in detail.
Bubbling, preventDefault, and Forms
Event binding uses native DOM events, so native behavior still applies:
- Bubbling. A
(click)on a parent<div>also fires for clicks on its child buttons. Call$event.stopPropagation()in the child's handler if the parent must not react. - Default actions. Clicking a link navigates, and submitting a form reloads the page. Call
$event.preventDefault()to stop that.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-subscribe',
template: `
<form (submit)="onSubmit($event)">
<input type="email" (input)="onEmail($event)" required />
<button type="submit">Subscribe</button>
</form>
<p>{{ status() }}</p>
`
})
export class SubscribeComponent {
email = signal('');
status = signal('');
onEmail(event: Event) {
this.email.set((event.target as HTMLInputElement).value);
}
onSubmit(event: SubmitEvent) {
event.preventDefault();
this.status.set(`Subscribed ${this.email()}`);
}
}The handler parameter is typed SubmitEvent here. Under strict DOM event typing, Angular infers $event from the event name, so (submit) gives a SubmitEvent and (keydown) gives a KeyboardEvent.
Common Errors
- Using
onprefixes like(onclick): the handler never runs, and nothing reports an error. - Forgetting the call parentheses, as in
(click)="save". - Reading
$event.target.valuedirectly in a strict template, which fails to compile. - Forgetting
preventDefault()on a plain form submit, so the page reloads and wipes the state. - Doing heavy work inside a high-frequency event such as
(mousemove)or(scroll). Every event triggers change detection, so keep these handlers small.
Event binding also works on your own components. A child component can expose events that a parent listens to with the same (name) syntax. The chapter on inputs and outputs covers that.
Exercise
A template contains <input (keydown.enter)="search()" />. The user types a query and presses Shift+Enter. Does search() run? Why or why not?
Show answer
No. Key filters match modifiers exactly. keydown.enter fires only when Enter is pressed with no modifiers, so Shift+Enter needs its own binding, (keydown.shift.enter).
Exercise
Under strict template checking, (input)="query.set($event.target.value)" fails to compile. Explain why, and rewrite it in the recommended typed way.
Show answer
$event.target has the type EventTarget | null, which has no value property, and templates cannot use as casts. Pass the event to a method instead: (input)="onQuery($event)", with onQuery(event: Event) { this.query.set((event.target as HTMLInputElement).value); } in the class.
Exercise
A card <div (click)="openDetails()"> contains a <button (click)="deleteItem()">Delete</button>. Clicking Delete also opens the details. Fix it without moving any elements.
Show answer
The click bubbles from the button to the div. Pass the event and stop it: <button (click)="deleteItem(); $event.stopPropagation()">, or call event.stopPropagation() inside a deleteItem(event: MouseEvent) method.