0
0
Angularframework~5 mins

Event binding with parentheses in Angular

Choose your learning style9 modes available
Introduction

Event binding lets your app respond when users do things like click buttons. Parentheses around an event name tell Angular to listen for that event.

When you want to run code after a user clicks a button.
When you need to react to keyboard presses in a form.
When you want to handle mouse movements or hovers.
When you want to update your app after a user submits a form.
When you want to trigger a function after a user changes a dropdown selection.
Syntax
Angular
<button (click)="doSomething()">Click me</button>

The parentheses () around click tell Angular to listen for the click event.

The value inside quotes is the function to run when the event happens.

Examples
Runs sayHello() when the button is clicked.
Angular
<button (click)="sayHello()">Say Hello</button>
Runs onKeyUp function on every key press inside the input. $event gives details about the key event.
Angular
<input (keyup)="onKeyUp($event)">
Runs onChange with the selected value when the dropdown changes.
Angular
<select (change)="onChange($event.target.value)">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>
Sample Program

This component shows a button and a count. Each time you click the button, the increment() method runs and adds 1 to count. The count updates on the screen.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-click-example',
  template: `
    <button (click)="increment()">Click me</button>
    <p>You clicked {{count}} times.</p>
  `
})
export class ClickExampleComponent {
  count = 0;

  increment() {
    this.count++;
  }
}
OutputSuccess
Important Notes

Use parentheses only around the event name, never around the function call.

You can pass event details using $event inside the function.

Event binding works with many events like click, keyup, change, and more.

Summary

Parentheses around an event name tell Angular to listen for that event.

When the event happens, Angular runs the function you specify.

This helps your app respond to user actions like clicks and key presses.