AI Hints
Home›Angular Tutorial›Property Binding, Event Binding and ng generate component
Angular · Lesson 23 of 120

Event Binding

(event)="handler()".

⏱ 2 min read▶ Video at 28:05🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Pages must react to the user. Clicks, typing, and key presses are all events. Angular listens with round brackets.

  • React to the user
  • Clicks and typing
  • Round brackets

Round brackets

Round brackets around an event name, like click, listen for that event. The right side runs when it happens, usually a method call. Dollar event is the browser's event object, if you need it. Data flows from the page, into the class.

keyvalue
(click)="add()"on click
(input)="onType($event)"on typing
$eventthe event object
Directionpage → class

Handling a click

Click calls add to basket. The method logs a line, and changes the message. We click the button once. Run it. The log appears, and the message on the page has changed.

app.tstypescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="addToBasket()">Add Dune to the basket</button>
    <p>{{ message }}</p>
  `,
})
export class App {
  message = 'Your basket is empty.';

  addToBasket() {
    console.log('Button clicked');
    this.message = 'Dune was added to your basket.';
  }
}
Output
Button clicked
Also uses actions.json
[{"click": "button"}]

Reading what was typed

Input fires on every key press. On type reads the text from the event's target, the input box, and stores it. The search button logs the query. We type Dune, and click search. Run it. The query reached the class, and was logged.

app.tstypescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input placeholder="Search books" (input)="onType($event)">
    <button (click)="search()">Search</button>
  `,
})
export class App {
  query = '';

  onType(event: Event) {
    this.query = (event.target as HTMLInputElement).value;
  }

  search() { console.log(`Searching for: ${this.query}`); }
}
Output
Searching for: Dune
Also uses actions.json
[{"type": "input", "text": "Dune"}, {"click": "button"}]

Summary

Round brackets listen for events, and run a method. Dollar event gives the event details. Next, generating components with the CLI.

Key takeaways
  • (click)
  • (input)
  • $event
Next up: ng generate component — the CLI does the typing