Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 74 ยท Templates and Data Binding

Event Binding and $event

Learn Angular event binding - (click), the $event object, key filters like (keydown.enter), handler methods, preventDefault and how outputs use the same syntax.

Property binding sends data down from your component into the template. Event binding sends things up: a click, a key press, a form submit, an input change. You write the event name in parentheses and give it a statement to run: (click)="save()". When the event fires, Angular runs the statement, and (with signals or normal change detection) the screen updates.

This lesson covers the (event) syntax, the $event object, key filters such as (keydown.enter), calling methods, preventing default browser behavior, and how the exact same syntax is used for events that your own components emit. It builds on property and attribute binding.

Real Angular needs its compiler, so the Angular code in this lesson is read-only. The runnable <TryIt> examples are stand-ins: plain TypeScript and JavaScript that re-create how event names and key filters are matched, so you can experiment.

The (event) syntax

HTML
<button type="button" (click)="increment()">+1</button>
<input (focus)="hint.set('Type a name')" (blur)="hint.set('')" />
<form (submit)="save()">...</form>

The name in parentheses is the name of a DOM event (click, input, keydown, submit, focus, mouseenter...) or of an output of a component or directive. The right-hand side is a statement, not an expression: it may have side effects, it may call methods and it may chain several statements with semicolons. It cannot declare variables.

Handlers usually call a method on the component class, because that keeps the template small and the logic testable:

TypeScript
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}</p>
    <button type="button" (click)="increment()">+1</button>
    <button type="button" (click)="reset()">Reset</button>
  `,
})
export class CounterComponent {
  count = signal(0);

  increment(): void {
    this.count.update((n) => n + 1);
  }

  reset(): void {
    this.count.set(0);
  }
}

Short, obvious one-liners can stay in the template, such as (click)="open.set(true)". Anything with branching belongs in a method.

The $event object

Inside a handler, the special name $event holds the event object the browser passed to the listener. You hand it to your method like any other argument:

HTML
<input (input)="onType($event)" />
<button (click)="onPick(item, $event)">Pick</button>
TypeScript
onType(event: Event): void {
  const input = event.target as HTMLInputElement;
  this.query.set(input.value);
}

onPick(item: Item, event: MouseEvent): void {
  event.stopPropagation(); // do not let the click bubble to the row
  this.selected.set(item);
}

With strict templates (the default for new projects), Angular knows the type of $event for native events: KeyboardEvent for keydown, MouseEvent for click, and just Event for input. That is why event.target needs a cast: it is typed as EventTarget | null, because an event can bubble up from any element. You can sidestep the cast with a template reference variable, which hands you the element itself:

HTML
<input #box (input)="query.set(box.value)" />
<button type="button" (click)="query.set(''); box.value = ''">Clear</button>

#box names the input element, so box.value is its current text, and this is often the cleanest way to read an input. (Template references get their own lesson later: Template Refs, View Queries and Host Bindings.)

For events from your own components and directives (outputs), $event is whatever value the component emitted. If a <app-rating> emits a number, (rated)="score.set($event)" receives that number, not a DOM event. Inputs and Outputs shows how to define one.

Key events and key filters

Reacting to Enter or Escape is so common that Angular lets you filter right in the event name. Add the key after a dot:

HTML
<input
  #task
  (keydown.enter)="add(task.value); task.value = ''"
  (keydown.escape)="task.value = ''"
  placeholder="Press Enter to add, Esc to clear" />

The handler runs only for that key; every other key is ignored. Key names are the lowercase form of KeyboardEvent.key, so enter, escape, arrowdown, tab. Modifier keys come first and can be combined: (keydown.shift.enter), (keydown.control.s), (keydown.alt.arrowup). The modifier names are alt, control, meta and shift.

Use keydown for shortcuts and for "act on this key now", and keyup when you want to read the value after the character has landed. A text field's value is not yet updated during keydown, which surprises many beginners.

Here is a stand-in that parses a filter like keydown.shift.enter and decides whether a keyboard event matches it. It is simplified (the real parser knows a few more special names), but it shows exactly what a key filter means.

TypeScript Matching key filters like (keydown.shift.enter)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that plain Enter does not trigger the keydown.shift.enter handler, and Shift+Enter does not trigger keydown.enter: the modifiers must match exactly.

Preventing default behavior and stopping bubbling

Browsers do things on their own: a form submit reloads the page, a link navigates, the space bar scrolls. Angular does not cancel any of this for you. Call event.preventDefault() yourself:

HTML
<form (submit)="save($event)">
  <input name="title" />
  <button type="submit">Save</button>
</form>
TypeScript
save(event: SubmitEvent): void {
  event.preventDefault();
  // ...read the form and send it
}

(When you use Angular's forms directives, which you will meet in the forms chapter, the form directive cancels the browser's own submit for you and offers (ngSubmit), so you rarely call it by hand there.) Likewise, event.stopPropagation() stops the event from bubbling up to parent elements, which you need when a clickable row contains a clickable button.

sequenceDiagram
  participant U as User
  participant B as Browser DOM
  participant A as Angular listener
  participant C as Component
  U->>B: clicks the button
  B->>A: click event (bubbles up)
  A->>C: runs the handler, passing $event
  C->>C: updates its signals
  C-->>B: Angular refreshes the changed bindings

A click travels from the browser to your handler, and the updated state flows back into the template.

Some background: Angular attaches one real DOM listener per bound event on the element. Handlers run inside Angular's change detection, so when they change state the template is checked and updated. With signals, only the bindings that read a changed signal are refreshed.

A runnable stand-in: wiring handlers by name

Angular's compiler turns (click)="increment()" into "when this element gets a click, call increment on the component, then refresh." This HTML stand-in does the same job by hand: a small table maps event names to methods, and one tiny function wires everything up. Click the buttons, then type in the box and press Enter or Escape.

Event handlers wired from a table

Real Angular does not re-render everything after each event: it updates only what changed. The idea you should keep from this stand-in is the loop event, then handler, then state change, then refresh.

Common mistakes

  • Writing (click)="save" without parentheses. That evaluates the method but never calls it; write save().
  • Reading an input in keydown and getting the old value; use keyup or (input).
  • Expecting preventDefault() to be automatic. It is not, except where an Angular directive such as ngSubmit does it.
  • Putting long logic in the template. Move anything with if or loops into a method.
  • Mixing up outputs and DOM events. (selected) on a component listens to an output named selected, not to a DOM event, so $event is the emitted value.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $event contain in <button (click)="onPick($event)">?

    For DOM events, $event is the event object the browser passed to the listener. For component outputs it is the emitted value instead.
  2. 2. Which handler runs only when the user presses Shift and Enter together?

    Key filters list the modifiers first, then the key, separated by dots. Plain (keydown.enter) does not fire when Shift is held, because the modifiers must match exactly.
  3. 3. Does Angular automatically call preventDefault() for a (submit) handler on a plain form?

    Angular does not change browser defaults on its own. Without preventDefault the browser would submit the form and reload the page.
  4. 4. Why is event.target typed as EventTarget | null in a handler for (input)?

    The target is whichever element started the event. Cast it, or use a template reference variable such as #box and read box.value.

Summary

  • (event)="statement" runs a statement when a DOM event or a component output fires.
  • $event is the browser's event object for DOM events and the emitted value for outputs.
  • Key filters such as (keydown.enter) and (keydown.control.s) limit a handler to specific keys; modifiers come first and must match exactly.
  • Call event.preventDefault() and stopPropagation() yourself; Angular does not do it for you.
  • Keep templates thin: call a method for anything beyond a one-liner, and use #ref to read inputs without casts.
  • The <TryIt> examples are stand-ins; the Angular snippets are read-only.

Next: Two-Way Binding and model()