Event binding
Event binding allows you to listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.
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()
.<button (click)="onSave()">Save</button>
- 1.
- 2.The directive then calls
EventEmitter.emit(data)
to emit an event, passing in message data, which can be anything. - 3.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)content_copy<img src="{{itemImageUrl}}" [style.display]="displayNone">
<span [style.text-decoration]="lineThrough">{{ item.name }}
</span>
<button (click)="delete()">Delete</button>
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)content_copy// This component makes a request but it can't actually delete a hero.
@Output() deleteRequest = new EventEmitter<Item>();
delete() {
this.deleteRequest.emit(this.item);
this.displayNone = this.displayNone ? '' : 'none';
this.lineThrough = this.lineThrough ? '' : 'line-through';
}
The hosting parent component binds to the
deleteRequest
event of the ItemDetailComponent
as follows.src/app/app.component.html (event-binding-to-component)content_copy<app-item-detail (deleteRequest)="deleteItem($event)" [item]="currentItem"></app-item-detail>
Last modified 2yr ago