Introduction
Event binding let’s Angular listen and interact with user-based actions such as clicks, keystrokes, movements using the mouse or touchpad, and touch. Angular takes care of configuring the event handler for the event that is targeted. The event is then raised either by a directive or component. The statement in the template is then executed by the handler. An action is then carried out by the statement in the template due to the event being raised.
How event binding works in Angular
Event binding in Angular has its own syntax. It is the event name surrounded by round brackets ()
, followed by an equal sign, and then the name of a statement.
Example
<button (click)="close()">Cancel</button>
Let’s break this down:
(click)
- The event name
close()
- The statement
In the above example, event binding is listening for the click event to occur on the button. Once this happens, a call is made to the close
method that is part of the same component as the button any time the user clicks on the button.
Custom events
Angular allows you to create custom events using EventEmitter.
Example:
app.component.html
app.component.ts
Custom events work in the following way:
-
EventEmitters are created by directives and in turn are exposed as a type of property.
-
The directive which created the EventEmitter makes a call to
EventEmitter.emit(dataToBePassed)
. In our casethis.clickedButton.emit(choice)
. -
We use the
@Input
and@Output
directives in order to listen for the event by binding to the EventEmitter and gaining access to the data that is being passed by the EventEmitter (choice
) through leveraging the object$event
.
How to determine an event target
In order to determine an event target simply add $event
in your template. For example, in the example above, we can pass $event
as follows:
We would also need to change the type for the choice parameter in app.component.ts
from boolean
to any
. Changing the type to any
is only done for demonstrative purposes and generally should not be used when writing production code.
If we console the $event
object, we get the following:
The $event
object usually has within it what the method that handles the event needs.
The event that is targeted also determines how the $event
object will be shaped. If the event that is targeted is “a native DOM element event”, then the $event
object “is a DOM event object” (e.g. target
; target.value
).[1]