Loading...

Event Binding in Angular

Event binding in Angular is used to capture user interactions (such as clicks, keypresses, mouse movements, etc.) and trigger corresponding methods in the component.

Syntax

Event binding uses parentheses ( ) around the event name:

<element (event)="method()"></element>

Here, the event is triggered, and the corresponding method in the component is executed.

Example

Component (TypeScript) - app.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
                })
export class AppComponent {
  message = 'Click the button to see a message';
  showMessage() {
  this.message = 'Button clicked! Event Binding works!';
  }
}

Template (HTML) - app.component.html

<h2>{{ message }}</h2>
<!-- Event Binding Example -->
<button (click)="showMessage()">Click Me</button>

How It Works

  • (click)="showMessage()" → When the button is clicked, the showMessage() method is called.
  • The message variable is updated in the component.
  • Angular automatically updates the view to reflect the new message.

Commonly Used Events

Event Description Example
(click) Triggered when an element is clicked. <button (click)="doSomething()">Click Me</button>
(keyup) Fires when a key is released. <input (keyup)="onKeyPress($event)">
(mouseover) Triggered when the mouse moves over an element. <div (mouseover)="onHover()">Hover me</div>
(input) Triggered when an input value changes. <input (input)="updateValue($event)">

Example with Event Parameter

Component (TypeScript) - app.component.ts

import { Component } from '@angular/core';
  @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
                })
export class AppComponent {
  inputText = '';

  onInput(event: any) {
    this.inputText = event.target.value;
  }
}

Template (HTML) - app.component.html

<input (input)="onInput($event)" placeholder="Type something">
<p>You typed: {{ inputText }}</p>

Event Binding with Multiple Statements

We can execute multiple statements using ; inside the event binding.

TypeScript - app.component.ts

logMessage() {
    console.log('Button clicked! Count:', this.count);
  }

Template (HTML) - app.component.html

<button (click)="count = count + 1; logMessage()">Increase Count</button>

Event Binding with Template Reference Variables

We can directly reference an input field and pass it to the method.

Template (HTML)

<input #userInput type="text">
<button (click)="showAlert(userInput.value)">Submit</button>

Component (TypeScript)

showAlert(value: string) {
  alert('User Input: ' + value);
}

Conclusion

Event binding in Angular allows interaction between the user and the application. It helps capture user input and respond accordingly.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!