Event binding
Event binding allows you to listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.
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. In the following example, the target event name is click
and the template statement is onSave()
.
Custom events with EventEmitter
EventEmitter
Directives typically raise custom events with an Angular EventEmitter as follows.
The directive creates an
EventEmitter
and exposes it as a property.The directive then calls
EventEmitter.emit(data)
to emit an event, passing in message data, which can be anything.Parent directives listen for the event by binding to this property and accessing the data through the
$event
object.
Consider an ItemDetailComponent
that presents item information and responds to user actions. Although the ItemDetailComponent
has a delete button, it doesn't contain the functionality to delete the hero. It can only raise an event reporting the user's delete request.src/app/item-detail/item-detail.component.html (template)
The component defines a deleteRequest
property that returns an EventEmitter
. When the user clicks Delete, the component invokes the delete()
method, telling the EventEmitter
to emit an Item
object.src/app/item-detail/item-detail.component.ts (deleteRequest)
The hosting parent component binds to the deleteRequest
event of the ItemDetailComponent
as follows.src/app/app.component.html (event-binding-to-component)
Last updated
Was this helpful?