Angular - Event Binding


Event binding allows developers to respond directly to a variety of user actions such as clicks, mouse movements, and keyboard inputs. It is achieved using the () syntax to bind an event to a method in your component.

Syntax:

(event)="expression"
app/src/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  msg(){
    alert("Welcome");
  }
}

msg() Defines a method msg that displays an alert with the message "Welcome".

app/src/app.component.html
<button (click)="msg()">Click Me</button>

When the button is clicked, the msg method will be called, displaying an alert with the message "Welcome".

Run the Angular Application use the command is given below

ng serve

Copy the URL: http://localhost:4200/ and run in your browser

Output 1

Angular Event Binding Output1

Output 2

Angular Event Binding Output2

Prev Next