Event Binding
Data Flow : Element to Component
Users don't just stare at the screen. They enter text into input boxes. They pick items from lists. They click buttons.
The only way to know about a user action is to listen for certain events such as keystrokes, mouse movements, clicks, and touches.
Such user actions may result in a flow of data in the opposite direction: from an element to a component.
Event Binding Syntax
Event binding syntax consists of a target event name within parentheses ( )
on the left of an =
sign, and a quoted template statement on the right.
<button (click)="onSave()">Save</button>
<button on-click="onSave()">On Save</button>
Element events may be the more common targets, but Angular looks first to see if the name matches an event property of a known directive, as it does in the following example:
<!-- `myClick` is an event on the custom `ClickDirective` -->
<div (myClick)="clickMessage=$event" clickable>click with myClick</div>
$event object
When the event is raised, the handler executes the template statement. The template statement typically involves a receiver, which performs an action in response to the event, such as storing a value from the HTML control into a model.
The shape of the event object is determined by the target event.
If the target event is a native DOM element event, then
$event
is a DOM event object, with properties such astarget
andtarget.value
. The properties of an$event
object vary depending on the type of DOM event. For example, a mouse event includes different information than a input box editing event.
<input [value]="currentHero.name"
(input)="currentHero.name=$event.target.value" >
If the event belongs to a directive (recall that components are directives), $event has whatever shape the directive decides to produce.
[R]
Customize event
Directives typically raise custom events with an Angular EventEmitter
.
The directive creates an EventEmitter and exposes it as a property. The directive calls EventEmitter.emit(payload)
to fire an event, passing in a message payload, which can be anything. Parent directives listen for the event by binding to this property and accessing the payload through the $event
object.
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 a Hero object.
src/app/hero-detail.component.ts
<div>
<img src="{{heroImageUrl}}">
<span [style.text-decoration]="lineThrough">
{{prefix}} {{hero?.name}}
</span>
<button (click)="delete()">Delete</button>
</div>`
src/app/hero-detail.component.ts
deleteRequest = new EventEmitter<Hero>();
delete() {
this.deleteRequest.emit(this.hero);
}
src/app/app.component.html
<app-hero-detail (deleteRequest)="deleteHero($event)" [hero]="currentHero"></app-hero-detail>
Last updated
Was this helpful?