Angular 2 Event Binding Tutorial
See how event bindings listen for DOM events such as
standard HTML elements such as
In the text below, when you see a word or phrase, click on it to highlight the source code.
Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.
Event Binding with Parentheses
We handle DOM events using parentheses and template statements.
When an event in
The string in quotes is a template statement. Template statements respond to an
Here we simply
automatically set to the target event, which in this case is of type
We can use this object to access X and Y
Here is the output from this component. Move the pointer around the inner box and click,
double click and right click on the mouse whilst holding down the
Keyboard events follow the same pattern;
Template statements are expected to change the state of the application based on the user's input.
Technically, they can contain statements that directly alter data such as
"key = $event.key" but this is usually best handled by
Here is the output from this component.
Drag and Drop Example
Let's look at event binding in action using a drag and drop example.
We bind to the
and set the
event on the container executes a template statement which calls the
This method checks the
value and, if it is true, adjusts the
Here is the output. Click on the green box to move it around within the gray container.
To find out more about Angular components, check out these tutorials.
- Templates - introduction to inline and external templates.
- Interpolation - use curly braces and template expressions to output data.
- Property Binding - update standard properties on the DOM using template expressions.
- Two-way Binding - combine property and event binding to create two-way binding with
- Input Binding - bind to
<input>fields such as
- Built-in Directives - use
ngStyleto transform the DOM.
- Component Input Output - use
@Outputto pass data in to and out of a component.
- Event Binding on angular.io
- Template Statements on angular.io
- DOM Event Reference on Mozilla Developer Network