Angular
Search…
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().
1
<button (click)="onSave()">Save</button>
Copied!

Custom events with EventEmitter

Directives typically raise custom events with an Angular EventEmitter as follows.
  1. 1.
    The directive creates an EventEmitter and exposes it as a property.
  2. 2.
    The directive then calls EventEmitter.emit(data) to emit an event, passing in message data, which can be anything.
  3. 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)
1
content_copy<img src="{{itemImageUrl}}" [style.display]="displayNone">
2
<span [style.text-decoration]="lineThrough">{{ item.name }}
3
</span>
4
<button (click)="delete()">Delete</button>
Copied!
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)
1
content_copy// This component makes a request but it can't actually delete a hero.
2
@Output() deleteRequest = new EventEmitter<Item>();
3
4
delete() {
5
this.deleteRequest.emit(this.item);
6
this.displayNone = this.displayNone ? '' : 'none';
7
this.lineThrough = this.lineThrough ? '' : 'line-through';
8
}
Copied!
The hosting parent component binds to the deleteRequest event of the ItemDetailComponent as follows.src/app/app.component.html (event-binding-to-component)
1
content_copy<app-item-detail (deleteRequest)="deleteItem($event)" [item]="currentItem"></app-item-detail>
Copied!
Last modified 1yr ago