Back to course

Event Binding ( )

The Complete Angular Developer: From Zero to Hero

12. Event Binding ( )

Event binding allows the application to respond to user interactions, such as clicks, key presses, or form submissions. It is a way to bind a component method to an event fired by an HTML element.

Syntax

Event binding uses parentheses (( )) around the target element event. The value is a statement that executes a component method.

html <element (event-name)="componentMethod($event)">

Example: Handling Clicks

Component Class (counter.component.ts):

typescript export class CounterComponent { count: number = 0;

increment() { this.count++; }

decrement() { if (this.count > 0) { this.count--; } } }

Template (counter.component.html):

html

Current Count: {{ count }}

<button (click)="increment()">+

<button (click)="decrement()">-

The Event Object ($event)

Many DOM events pass an event object. You can access this object in the binding expression using the $event keyword.

Example: Capturing Input Data

html <input (input)="onInput($event)" placeholder="Type here">

Current value: {{ inputValue }}

typescript export class InputComponent { inputValue: string = '';

onInput(event: Event) { // Use type assertion to access the target's value property this.inputValue = (event.target as HTMLInputElement).value; } }