Event Binding - Click Event

Introduction

  1. Event Binding is a very important topic in Angular.
  2. Whenever you want to perform any action on the UI, you need Event Binding.
  3. Examples of events:
  4. Mouse events
  5. Keyboard events
  6. Click event
  7. Change event
  8. Select event
  9. All these come under Event Binding.

This topic will be covered in multiple parts, because Angular has many events.

Important events will be definitely covered.


What is Event Binding?

Definition (Simple):

When you declare an event in an HTML file (like button click or input change) and call a function written in the component’s TypeScript file, this is called Event Binding.

You bind a TypeScript function with an HTML event.


First Example – Button Click Event

HTML

<button (click)="callMe()">Click Me</button>


TypeScript (app.component.ts)

callMe() {
alert('Hello Angular 21');
}

Explanation

  1. (click) is the event.
  2. callMe() is the function from the TS file.
  3. Parentheses () are mandatory.
  4. Clicking the button shows an alert: Hello Angular 21

This is Event Binding, because the click event is bound to a function.


Other Events (Mentioned)

  1. (change) → for input or dropdown change
  2. (input) → for input typing
  3. These will be covered later.

For now, focus is on click event.


Counter Example Using Event Binding

Step 1: Property Declaration

count = 0;

Step 2: Counter Function

counter() {
this.count++;
console.log(this.count);
}

Step 3: Button Click

<button (click)="counter()">+</button>

Step 4: Display Value Using Interpolation

<span>{{ count }}</span>

Important Rule (Common Mistake)

  1. Inside TS file function → use this.count
  2. Inside HTML file → use count (no this)


Adding Minus Button

HTML

<button (click)="counter('plus')">+</button>
<button (click)="counter('minus')">-</button>
<span>{{ count }}</span>


TypeScript with Parameter

count = 0;

counter(action: string) {
if (action === 'minus') {
this.count--;
} else {
this.count++;
}
}


Prevent Counter from Going Below Zero

Updated Logic

counter(action: string) {
if (action === 'minus' && this.count > 0) {
this.count--;
} else if (action === 'plus') {
this.count++;
}
}

Result

  1. Counter increases with +
  2. Counter decreases with -
  3. Counter stops at 0 and never goes negative


Calling One Function from Another Function

Function Example

showUserName() {
alert('Hello');
}


Call Function on Button Click

<button (click)="showUserName()">Show</button>


Calling Function Inside Another Function

counter(action: string) {
this.showUserName();
}

👉 Use this.functionName() to call another function inside TS.