Event Binding - Click Event
Introduction
- Event Binding is a very important topic in Angular.
- Whenever you want to perform any action on the UI, you need Event Binding.
- Examples of events:
- Mouse events
- Keyboard events
- Click event
- Change event
- Select event
- 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
(click)is the event.callMe()is the function from the TS file.- Parentheses
()are mandatory. - 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)
(change)→ for input or dropdown change(input)→ for input typing- 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)
- Inside TS file function → use
this.count - Inside HTML file → use
count(nothis)
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
- Counter increases with
+ - Counter decreases with
- - 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.