Angular FAQ: Top Questions
15. What is Event Binding in Angular?
Event binding in Angular is a mechanism that allows your application to respond to user actions in the DOM — such as clicks, keystrokes, mouse movements, and more — by binding those events to methods defined in the component class.
Event binding uses the syntax (eventName)="expression", where eventName is the name of the DOM event (e.g., click, input, keydown), and expression is usually a method call or some logic defined in the component.
-
Syntax:
(click)="onClickHandler()"– Binds a click event to a method.(keyup)="logInput($event)"– Captures keyup events with access to the native event object.
-
Use Cases:
- Handling user interactions such as form submissions, button presses, or navigation triggers.
- Reacting to real-time input changes, validating user entries, or invoking service logic.
-
Accessing Event Object:
-
Angular allows access to the native DOM event using the special
$eventvariable. -
Example:
(input)="updateText($event)"
-
Angular allows access to the native DOM event using the special
// demo.component.html
<button (click)="showMessage()">Click Me</button>
// demo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html'
})
export class DemoComponent {
showMessage() {
alert('Button clicked!');
}
}
Explanation of the Example Code:
-
The
<button>element uses Angular’s event binding syntax(click)="showMessage()". -
When the button is clicked, the
showMessage()method in the component is executed. -
This method displays a browser alert dialog saying
"Button clicked!".
Event binding connects your UI to the underlying logic in a clean and intuitive way, ensuring that your Angular application responds interactively to user actions.
