Skip to content

Instantly share code, notes, and snippets.

@MrGrigri
Last active February 23, 2025 21:41
Show Gist options
  • Save MrGrigri/c3fbaab69ac97891e81f5884e3ed8f76 to your computer and use it in GitHub Desktop.
Save MrGrigri/c3fbaab69ac97891e81f5884e3ed8f76 to your computer and use it in GitHub Desktop.
Angular Konami Service
import { isPlatformBrowser } from '@angular/common';
import {
EventEmitter,
inject,
Injectable,
Output,
PLATFORM_ID,
} from '@angular/core';
@Injectable({ providedIn: 'root' })
export class KonamiService {
#inputSequence: Array<string> = [];
#konamiCode: Array<string> = [
'ArrowUp',
'ArrowUp',
'ArrowDown',
'ArrowDown',
'ArrowLeft',
'ArrowRight',
'ArrowLeft',
'ArrowRight',
'b',
'a',
];
#platformId: {} = inject(PLATFORM_ID);
#successful: boolean = false;
get successful(): boolean {
return this.#successful;
}
@Output() konamiCodeActivated = new EventEmitter<void>();
constructor() {
this.initialize();
}
initialize() {
if (isPlatformBrowser(this.#platformId)) {
this.#addWindowKeydownHandler();
}
}
destroy() {
this.#removeWindowKeydownHandler();
}
#addWindowKeydownHandler() {
window.addEventListener(
'keydown',
this.#handleWindowKeydownEvent.bind(this)
);
}
#removeWindowKeydownHandler() {
window.removeEventListener(
'keydown',
this.#handleWindowKeydownEvent.bind(this)
);
}
#handleWindowKeydownEvent(event: KeyboardEvent) {
this.#inputSequence.push(event.key);
if (this.#inputSequence.length > this.#konamiCode.length) {
this.#inputSequence.shift();
}
if (this.#inputSequence.join(',') === this.#konamiCode.join(',')) {
this.konamiCodeActivated.emit();
this.#inputSequence = [];
this.#successful = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment