How to import a provider (plugin) from another module?

54 Views Asked by At

I found a very helpful Angular plugin on StackBlitz (code below)

You can directly bind to the click event with modifiers like so (click.shift)="doSomething()"

When I put the plugin in my module it works just fine

@NgModule({
  // ...
  providers: [
    {
      provide: EVENT_MANAGER_PLUGINS,
      useClass: ClickModifiersPlugin,
      multi: true,
    },
  ],
})

I have put shared components, general imports etc in a core module which is then the first import in every other module. So naturally I wanted to move the provider to my core module as well. But when I do that, the (click.shift) event won't work any longer. The constructor is not even called.

So my question is: How do I import a plugin provider from another module?


Here is the code of the plugin

import { Injectable } from '@angular/core';
import { EventManager } from '@angular/platform-browser';
import { fromEvent } from 'rxjs';
import { filter, tap } from 'rxjs/operators';

const APPLE_PATTERN = /(mac|iphone|ipod|ipad)/i;
const EVENT_PATTERN = /^click(\.(shift|alt|ctrl)){1,3}$/;

@Injectable()
export class ClickModifiersPlugin {
  manager: EventManager;

  addEventListener(
    target: HTMLElement,
    eventName: string,
    originalHandler: any,
  ): Function {
    const isApple = APPLE_PATTERN.test(navigator.platform);
    const [name, ...keys] = eventName.split(".");
    const modifiers = keys.map(
      key => isApple && key === 'ctrl' ? 'metaKey' : key + 'Key'
    );

    const subscription = fromEvent(target, 'click').pipe(
      filter(e => modifiers.every(modifier => e[modifier])),
    ).subscribe(originalHandler);

    return () => subscription.unsubscribe();
  }

  supports(eventName: string): boolean {
    return EVENT_PATTERN.test(eventName);
  }
}
0

There are 0 best solutions below