Event Binding
When a user clicks a button, types in an input, or moves the mouse, your app needs to respond. Event binding lets you listen to these user actions and run component methods in response.
Event binding syntax is simple: wrap the event name in parentheses and assign a template statement.
Basic examples:
<button (click)="onClick()">Click me</button>
<input (input)="onInput($event)">
<div (mouseenter)="onMouseEnter()" (mouseleave)="onMouseLeave()">
Hover over me
</div>
Corresponding component methods:
export class EventDemoComponent {
onClick() {
console.log('Button clicked');
}
onInput(event: any) {
console.log('Input value:', event.target.value);
}
onMouseEnter() {
console.log('Mouse entered');
}
onMouseLeave() {
console.log('Mouse left');
}
}
You can pass the
$event object to get details about the event. For form inputs, you can also use template reference variables:<input #myInput (input)="onInput(myInput.value)">
<p>You typed: {{ myInput.value }}</p>
Two Minute Drill
- Event binding listens to user actions like clicks, inputs, mouse movements.
- Syntax:
(eventName)="methodName()". - Pass
$eventto access event details. - Use template reference variables (#var) to access DOM elements directly.
- Event binding keeps your UI interactive and responsive.
Need more clarification?
Drop us an email at career@quipoinfotech.com
