Event binding
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.
See the live example for a working example containing the code snippets in this guide.
Prerequisites
Binding to events
To bind to an event you use the Angular event binding syntax. This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right.
Create the following example; the target event name is click
and the template statement is onSave()
.
<button (click)="onSave()">Save</button>
The event binding listens for the button's click events and calls the component's onSave()
method whenever a click occurs.
Determining an event target
To determine an event target, Angular checks if the name of the target event matches an event property of a known directive.
Create the following example: (Angular checks to see if myClick
is an event on the custom ClickDirective
)
<h4>myClick is an event on the custom ClickDirective:</h4> <button type="button" (myClick)="clickMessage=$event" clickable>click with myClick</button> {{clickMessage}}
If the target event name, myClick
fails to match an output property of ClickDirective
, Angular will instead bind to the myClick
event on the underlying DOM element.
Binding to passive events
This is an advanced technique that is not necessary for most applications. You may find this useful if you want to optimize frequently occurring events that are causing performance problems.
Angular also supports passive event listeners. For example, use the following steps to make a scroll event passive.
- Create a file
zone-flags.ts
undersrc
directory. - Add the following line into this file.
- In the
src/polyfills.ts
file, before importing zone.js, import the newly createdzone-flags
.
import './zone-flags'; import 'zone.js'; // Included with Angular CLI.
After those steps, if you add event listeners for the scroll
event, the listeners will be passive
.
What's next
- For more information on how event binding works, see How event binding works.
- Property binding
- Text interpolation
- Two-way binding
© 2010–2022 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/event-binding