bertrandg
bertrandg

Reputation: 3207

Angular: How to use a custom EventPlugin only inside specific component instead of whole ngModule?

I have this angular event plugin: (copied from there)

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

    supports(eventName: string): boolean {
        return eventName.indexOf('undetected.') === 0;
    }

    addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
        const realEventName = eventName.slice(11);
        return this.manager.getZone().runOutsideAngular(() => this.manager.addEventListener(element, realEventName, handler));
    }
}

If I add it to module provider, it works perfectly everywhere in the app:

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent,... ],
  bootstrap:    [ AppComponent ],
  providers: [{
      provide: EVENT_MANAGER_PLUGINS,
      useClass: UndetectedEventPlugin,
      multi: true
  }]
})
export class AppModule {}

But, instead, if I add it to a specific component provider like this:

@Component({
  selector: 'hello',
  providers: [{
    provide: EVENT_MANAGER_PLUGINS,
    useClass: UndetectedEventPlugin,
    multi: true
  }],
  template: `<button (click)="test()">BTN 1: (click)="test()"</button><br><br>
             <button (undetected.click)="test()">BTN 1: (undetected.click)="test()"</button>`,
})
export class HelloComponent {
  test() {
    console.log('TEST FUNCTION')
  }
}

It doesn't works.
It seems to have to be global to whole application but I'm not sure about it..

Do you know a way to limit eventPlugin scope to a component?

Demo: https://stackblitz.com/edit/angular-jk4gpm?file=src%2Fapp%2Fhello.component.ts

Upvotes: 2

Views: 189

Answers (1)

Reactgular
Reactgular

Reputation: 54741

The EventManager is part of the Browser modules, and it receives all of the plugins as part of it's constructor dependencies.

/**
 * Initializes an instance of the event-manager service.
 */
constructor(plugins: EventManagerPlugin[], _zone: NgZone);

Once an instance of EventManager has been created, then no additional plugins can be added.

You should not use the providers dependencies to perform business logic. If you want to conditionally use the plugin, then add logic to the plugin. You can inject the plugin into your component to configure how it should work based upon the life-cycle of the component.

Upvotes: 1

Related Questions