Advertisement
Beginner Angular, Data Binding

How does event binding work in Angular, letting a component respond to a user action?

Short answer

You wrap an event name in parentheses inside your template, and set it equal to a method on your component class, which Angular calls automatically whenever that specific event, like a click or a key press, happens on that element.

Save Angular mock interview
Advertisement
AModel answer
You wrap an event name in parentheses inside your template, and set it equal to a method on your component class, which Angular calls automatically whenever that specific event, like a click or a key press, happens on that element.
@Component({
  selector: 'app-button',
  template: `<button (click)="handleClick()">Save</button>`
})
export class ButtonComponent {
  handleClick() {
    console.log('Button was clicked');
  }
}
Real-world example
A save button in a settings page calls a specific method to save the user's changes the moment they click it, using event binding to connect the click directly to that method.
Likely follow-ups
  • How do you access the actual event object, such as which key was pressed, inside an event binding?
  • Can you bind more than one event to the same element?
Related topics