Skip to content
Poul Kruijt edited this page Sep 14, 2022 · 8 revisions

Ng Event Options Wiki

Getting started

Prerequisites

Depends on latest Angular

"dependencies": {
  "@angular/common": "*",
  "@angular/core": "*"
}

Installation

To install the module using npm use:

npm i ng-event-options

Importing

If you are using the angular-cli, all you need to do is install and import the NgEventOptions module in your AppModule and you are good to go:

@NgModule({
    imports: [
        // ...,
        NgEventOptionsModule
    ],
    // ...
})
export class AppModule {}

Usage

To use the EventManager which comes with this module, you have to bind an event like you are used to, add a dot (.), and state your desired options after. Case is relevant, the order is not and everything defaults to false. As long as it makes sense you can use all the options together, apart from the preventDefault and passive, because this natively throws an error.

Options

  • p (creates a passive event)
  • c (captures the event in the capture phase)
  • o (after firing the event once, the listener will be removed)
  • n (add the event listener outside the NgZone)
  • s (stop the event from bubbling any further, using stopPropagation and stopImmediatePropagation)
  • d (preventing default browser behaviour using preventDefault
  • b (only add listener when current environment is a browser for usage in Angular Universal)
  • * (forces the usage of the ngEventOptions EventManager)

Operators

  • th{time = 50, immediate = 0} (throttles the event for the given time. Set immediate to start on the leading edge.
  • db{time = 50, immediate = 0} (debounces the event for the given time. Set immediate to start on the leading edge.

Examples

<button (mousedown.pcon)="onClick($event)">Click</button>

This will create a mousedown event on the button which is passive (p), will be fired on the capture (c) phase, will only be fired once (o), and is running outside the ngZone (n) .

<div (mousedown.sn)="$event"></div>

This creates an event which prevents bubbling up the DOM on mousedown

<div (mousemove.p|th{100})="onMouseMove($event)"></div>

This will create the event in passive mode, and only fire it after 100ms

<div (mousemove.*|db{100,1})="onMouseMove($event)"></div>

This will debounce the event with 100ms and will fire immediately after first invocation

Quirks

To add a keydown, keyup, keypress event with just one event option, you have to use the * ForceSymbol:

(these are all valid)

<input (keydown.p*)="onKeyDown($event)">
<input (keyup.o*)="onKeyUp($event)">
<input (keypress.*d)="onKeyPress($event)">
<input (keydown.pc)="onKeyDown($event)">

This is to prevent collision with the native Angular key mapping event handling