Giter VIP home page Giter VIP logo

ng2-events's Introduction

This version is compatible with Angular 9-16 (using Ivy)

  • For Angular 9-12 apps using View Engine, use version 4.2.2
  • For Angular 5-8, use version 4.2.2
  • For Angular 4, use version 3.1.0
  • For Angular 2, use version 2.0.0

Extensions to the Angular event handling to make use of additional events and allow for better control over change detection for high-performance applications:

  • Listen to events outside of the current element
  • Up/down event handlers for cross-browser touch/mouse events
  • Scroll-in/out event handlers to control behavior of elements within or outside the viewport
  • Listen to multiple events with a single handler
  • Unregister an event listener after the event fires once
  • Attach event listeners only when a condition is met
  • Listen to events without triggering change detection
  • Use Observables to fine-tune when to trigger change detection

Examples:

<div (outside.click)="close()">...</div>

<button (down)="activate()" (up)="deactivate()" (move)="active()">...</button>

<div (scroll-in)="activate()" (scroll-out)="deactivate()">...</div>

<input (multi.focus,select)="foo($event)" />

<button (once.click)="foo()">...</button>

<button [ev-condition]="cond" ev-events="click" (ev-fire)="foo()">...</button>

<button (undetected.click)="handleUndetectedClick()">...</button>

<button (observe.throttleTime-500.click)="handleClick()">...</button>

<button [ev-observe]="subject" [ev-events]="['mousedown', 'mouseup']">...</button>

Installation

npm install --save ng2-events

For applications using Angular Ivy, but without the Angular CLI, follow the docs on consuming partial Ivy code.

Usage

To use all of the events, import the Ng2EventsModule into your application or shared NgModule:

import {NgModule} from "@angular/core";
import {Ng2EventsModule} from "ng2-events";

@NgModule({
    imports: [Ng2EventsModule],
    exports: [Ng2EventsModule]
})
export class SharedModule {}

The recommended way is to only import the sub-modules for the features you need. Every module can either be imported from the package root or from its own sub-folder. Using deep imports is recommended if you only want to use a few of the modules in this library and your package manager does not support tree-shaking.

// top-level import
import {OutsideEventModule} from "ng2-events";

// deep import
import {OutsideEventModule} from "ng2-events/lib/outside";

If you use Rollup as your build system and you use deep imports, you have to add the CommonJS plugin:

import nodeResolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";

export default {
    // ...
    plugins: [
        nodeResolve({jsnext: true, module: true}),
        commonjs({ include: [
            'node_modules/rxjs/**',
            'node_modules/ng2-events/**'
        ]})
    ]
}

package.json main fields:

  • main: CommonJS library index (ES5)
  • jsnext:main: Flat ESM bundle (ES5)
  • module: Flat ESM bundle (ES5)
  • es2015: Flat ESM bundle (ES2015)

Additional Events

outside: Listen to events outside of an element

import {NgModule} from "@angular/core";
import {OutsideEventModule} from "ng2-events/lib/outside";

@NgModule({
    imports: [OutsideEventModule],
    exports: [OutsideEventModule]
})
export class SharedModule {}
<div (outside.click)="close()">...</div>

The event handler is called when an event is fired outside of the element and its children.

up/down/move: Cross-browser quick mouse/touch events

import {NgModule} from "@angular/core";
import {TouchEventModule} from "ng2-events/lib/touch";

@NgModule({
    imports: [TouchEventModule],
    exports: [TouchEventModule]
})
export class SharedModule {}
<button (down)="activate()" (up)="deactivate()" (move)="active()">...</button>

The up/down events are fired when one of the following events is fired on the element:

  • mousedown/mouseup
  • pointerdown/pointerup
  • touchstart/touchend

The move event is fired when one of the following events is fired on the element:

  • mousemove
  • pointermove
  • touchmove

Note that preventDefault() is called on the first event to occur to make sure that the event handler is only fired once. This prevents touch-enabled devices from firing the handler for both the touchstart and the mousedown event. Be aware that especially with the move event this might interfere with scrolling on touch-based devices!

For more complex touch gestures use the HammerJS integration.

scroll-in / scroll-out: Detect when an element is entering or leaving the viewport

import {NgModule} from "@angular/core";
import {ScrollEventModule, SCROLL_EVENT_TIME} from "ng2-events/lib/scroll";

@NgModule({
    imports: [ScrollEventModule],
    exports: [ScrollEventModule],
    providers: [
        {provide: SCROLL_EVENT_TIME, useValue: 500}
    ]
})
export class SharedModule {}
<div (scroll-in)="activate()" (scroll-out)="deactivate()">...</div>

This event handler reacts to the window's scroll, resize, and orientationchange events. It only checks the vertical scrolling within the window.

The configuration value SCROLL_EVENT_TIME sets a minimum time distance between checks to keep the performance impact low. The default value is 200ms.

Upon initialization the event handler is called directly if the element has the matching status (scroll-in is called if the element is visible in the viewport at rendering time, scroll-out is called otherwise). $event is true for the initial call, false for all subsequent calls.

Event Helpers

multi: Listen to multiple events at once

import {NgModule} from "@angular/core";
import {MultiEventModule} from "ng2-events/lib/multi";

@NgModule({
    imports: [MultiEventModule],
    exports: [MultiEventModule]
})
export class SharedModule {}
<input (multi.focus,select)="foo($event)" />

once: Only fire event listener once

import {NgModule} from "@angular/core";
import {OnceEventModule} from "ng2-events/lib/once";

@NgModule({
    imports: [OnceEventModule],
    exports: [OnceEventModule]
})
export class SharedModule {}
<button (once.click)="foo()">...</button>

The event listener is unregistered when the event is first fired. Note that it is reattached every time the element is newly rendered, especially inside *ngIf and *ngFor blocks when conditions or references change.

condition Directive: Only attach event listeners when a condition is met

import {NgModule} from "@angular/core";
import {ConditionEventDirectiveModule} from "ng2-events/lib/condition-directive";

@NgModule({
    imports: [ConditionEventDirectiveModule],
    exports: [ConditionEventDirectiveModule]
})
export class SharedModule {}

Listen to a single event:

<button [ev-condition]="isActive()"
    ev-events="click"
    (ev-fire)="handleClick($event)">...</button>

Listen to multiple events:

<button [ev-condition]="isActive()"
    [ev-events]="['mousedown', 'mouseup']"
    (ev-fire)="handleEvent($event)">...</button>

This directive also allows for listening to a dynamic set of events:

<button [ev-condition]="true"
    [ev-events]="events"
    (ev-fire)="handleEvent($event)">...</button>
export class ExampleComponent {
    
    events = ['mousedown'];
    
    changeEvents() {
        this.events = ['mouseup'];
    }
    
}

Note: If you just change events within the array, you have to manually change its reference so the change detector picks the change up and resets the event listeners:

this.events.push('click');
this.events = this.events.slice();

Change Detection

Note: The following event helpers will work for primitive events (such as 'click', 'mousemove', ...). More complex event plugins such as the HammerJS touch gesture integration take control over their own change detection handling.

undetected: Listen to events without triggering change detection

import {NgModule} from "@angular/core";
import {UndetectedEventModule} from "ng2-events/lib/undetected";

@NgModule({
    imports: [UndetectedEventModule],
    exports: [UndetectedEventModule]
})
export class SharedModule {}
<button (undetected.click)="handleClick()">...</button>
export class ExampleComponent implements OnInit {
    
    constructor(private zone: NgZone) {}
    
    handleClick() {
      if(someCondition) {
          this.zone.run(() => {
              ...
          });
      }
    }
}

This adds the event listener outside of the Angular zone, thus change detection is not triggered until you manually call NgZone.run() or a different event is fired within the Angular zone.

observe: Call an observable operator on events

import {NgModule} from "@angular/core";
import {ObserveEventModule} from "ng2-events/lib/observe";

@NgModule({
    imports: [ObserveEventModule],
    exports: [ObserveEventModule]
})
export class SharedModule {}
<button (observe.throttleTime-500.click)="handleClick()">...</button>

The method used must be present on the Observable object e.g. through an explicit import:

import 'rxjs/add/operator/throttleTime';

Note: As of RxJS 5.5, this approach is discouraged! (Read more)

With RxJS 6, it is deprecated and can only be used through the rxjs-compat module!

With RxJS 7, this is no longer possible.

To get finer-grained control and the possibility to add multiple observable operators use the observe Directive.

observe Directive: Fire events on an observable subject

import {NgModule} from "@angular/core";
import {ObserveEventDirectiveModule} from "ng2-events/lib/observe-directive";

@NgModule({
    imports: [ObserveEventDirectiveModule],
    exports: [ObserveEventDirectiveModule]
})
export class SharedModule {}

Observe a single event:

<button [ev-observe]="subject" ev-events="click">...</button>

Observe multiple events:

<button [ev-observe]="subject" [ev-events]="['mousedown', 'mouseup']">...</button>
export class ExampleComponent implements OnInit {
    
    public subject = new Subject();
    
    constructor(private zone: NgZone) {}
    
    ngOnInit() {
     this.subject
         .throttleTime(300)
         .filter(someCondition)
         // ...
         .subscribe($event => this.zone.run(() => this.handleEvent($event)));
    }
    
    private handleEvent($event: any) {
        // ...
    }
}

ng2-events's People

Contributors

dependabot[bot] avatar kryops avatar saitho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

pronebel

ng2-events's Issues

Switch to Angular CLI build process

Upgrading the library to newer versions of Angular is painful because it was created at a time when the Angular CLI was not around.

Switching the current manual build process using tsc, ngc and rollup to the Angular CLI should hopefully lead to easier upgrades.

Using one of your EventPlugin only inside a specific component.

Hi,
Your library is really usefull and interesting to understand how works angular, thanks for it!

I got a question not directly related to ng2-events but you seems to deeply understand how angular manage template event listeners "under the hood" so, maybe, you can help me (if that's not right place for, just close the issue..).

I got an angular library named angular-split and would like to use your UndetectedEventPlugin only inside my library component template.

I've tried to add the EventPlugin inside component providers but it's not recognized (no error but handler functions never called):

@Component({
    selector: 'as-split',
    providers: [{
            provide: EVENT_MANAGER_PLUGINS,
            useClass: UndetectedEventPlugin,
            multi: true
    }],
    template: `<div (undetected.click)="x()"></div>`,
})
export class SplitComponent {...}

On the contrary, if I add it inside library module providers, it works too well because all app using my library module have access to (undetected.anyevent) syntax which I don't want:

@NgModule({
    imports: [...], declarations: [...], exports: [...],
    providers: [
        {
            provide: EVENT_MANAGER_PLUGINS,
            useClass: UndetectedEventPlugin,
            multi: true
        }
    ]
})
export class AngularSplitModule {}

Any clue about it with your knowledge?

Move touch event

WIth (up) and (down) we are currently able to deal with the respective mouse, touch, pointer events.
However as of the current version it is not possible to do the same for the "move" event, that is triggered while the focus point moves.

touchend is equal to touchstart

Hi,

  • I have multiple controls
  • I start selection hover one control
  • I end selection hover another control

If i'm using mouse events it works fine. In mousedown I get the first control and in mouseup I get the second control.

But if i'm using touch events i'm getting only the first control. In touchstart I get the first control (it's correct) but in touchend I was expecting the second control - but get first control again.

I'm using version 4.1.0 with angular 5.2.2 and the relevant code is:

<ng-template ngFor let-item let-i="index" [ngForOf]="locals.Locals">
      <svg:g (down)="activate($event, item)" (up)="deactivate($event, item)" class="container small"

Thanks.

(down) firing twice on iPad Safari version 13+

My company uses this library mainly for the TouchEvent module. We found that on our iPads, after upgrading to iPadOs 13+, the (down) event would trigger our event handler twice. We did not see this behavior on our non-upgraded tablets. We also did not see this behavior on desktop.

iPadOs 13 brought Safari and some big changes to how iPadOs handles touch events and the 300ms delay.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.