Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Inject, Injectable} from '@angular/core';
- import {EventManager} from '@angular/platform-browser';
- import {DOCUMENT} from '@angular/common';
- import {Observable} from 'rxjs';
- type Options = {
- element: any;
- keys: string;
- }
- @Injectable({
- providedIn: 'root'
- })
- export class HotkeysService {
- private subscriptions: Map<string, Subscription> = new Map<string, Subscription>();
- defaults: Partial<Options> = {
- element: this.document
- };
- constructor(private eventManager: EventManager,
- @Inject(DOCUMENT) private document: Document) { }
- addShortcut(options: Partial<Options>) {
- const merged = { ...this.defaults, ...options };
- const event = `keydown.${merged.keys}`;
- const observable = new Observable(observer => {
- const handler = (e) => {
- e.preventDefault();
- observer.next(e);
- };
- const dispose = this.eventManager.addEventListener(
- merged.element, event, handler
- );
- return () => {
- dispose();
- };
- })
- this.subscriptions.set(event, observable);
- return observable;
- }
- removeShortcut(options: Partial<Options>){
- const subscription = this.subscriptions.get(`keydown.${options.keys}`);
- if(subscription != null){
- subscription.unsubscribe();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement