Skip to content

Latest commit

History

History
57 lines (31 loc) 路 2.73 KB

custom-events-management.md

File metadata and controls

57 lines (31 loc) 路 2.73 KB

Custom Events Handeling

Angular allows you to handle custom events, to extend existing ones or support new ones.

Handling user Events

Event Binding and the the HostListener decorator lets you listen for and respond to DOM events and components events.

<navbutton (click)="onClick($event)">You can click me<nav/button>

Event Handling by the EventManager

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

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.

Handle a custom event

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.

  1. support needs to return true if the stop modifier is present :

  1. Wrap the event's handler to stopPropagration and register the wrapper.
  2. Extract the original event name and registrer the event with the manager.

  1. 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.

<navbutton (click.stop)="onClick($event)">Propagation stopped<nav/button>

Try this .