Angular allows you to handle custom events, to extend existing ones or support new ones.
Event Binding and the the HostListener
decorator lets you listen for and respond to DOM events and components events.
Angular handles events using the EventManager
service. It has a set of plugins that extend the EventManagerPlugin
abstract class and delegates event subscription and handling to a plugin that supports particular events.
Angular has a few built-in plugins such as one dedicated to HammerJS events or the KeyEventsPlugin
responsible for handling composite events such as keydown.enter
.
EventManagerPlugin
is an abstract class with 2 methods to implement supports
and addEventListener
.
Plugings are loaded using the EVENT_MANAGER_PLUGINS
injection token and are provided to the BrowserModule
using multi: true
.
For the EventManager
to determine which plugin will handle the event, each plugin implements the supports
method.
The event manager will call addEventListener
on the first plugin where supports
returns true
.
Let's implement a plugin that will register events and call Event.stopPropagation()
on them.
This plugin will add the support for the .stop
modifier and we'll be able to register events like click.stop
.
support
needs to returntrue
if the stop modifier is present :
- Wrap the event's handler to
stopPropagration
and register the wrapper. - Extract the original event name and registrer the event with the manager.
- Add the plugin to the list of providers of the app.
You can now listen to the new custom events via Event bindings or the HostListener
decorator.
Try this .