Skip to content

Instantly share code, notes, and snippets.

@thehaseebahmed
Last active August 8, 2021 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thehaseebahmed/e20eaf974f7dd0b9071c80d52e5b8478 to your computer and use it in GitHub Desktop.
Save thehaseebahmed/e20eaf974f7dd0b9071c80d52e5b8478 to your computer and use it in GitHub Desktop.
An angular directive that enables you to trap focus to a certain HTML element. You can read more about it here: http://bit.ly/how-to-trap-focus
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[trapFocus]'
})
export class TrapFocusDirective implements AfterViewInit {
constructor(
private el: ElementRef
) {}
ngAfterViewInit() {
this.trapFocus(this.el.nativeElement);
}
trapFocus(element) {
element.addEventListener('keydown', function(e) {
const getActiveElement = () => {
if (document.activeElement?.shadowRoot) { return document.activeElement.shadowRoot.activeElement; }
else { return document.activeElement; }
};
const isTabPressed = e.keyCode === 9; // isTabPressed
if (!isTabPressed) return;
const focusableEls1 = element.querySelectorAll(
'a[href], button, textarea, input[type="text"],' +
'input[type="radio"], input[type="checkbox"], select'
);
const focusableEls = Array.from(focusableEls1).filter( (el: any) => !el.disabled);
const firstFocusableEl: any = focusableEls[0];
const lastFocusableEl: any = focusableEls[focusableEls.length - 1];
if ( e.shiftKey ) /* shift + tab */ {
if (getActiveElement() === firstFocusableEl) {
lastFocusableEl.focus();
e.preventDefault();
}
} else /* tab */ {
if (getActiveElement() === lastFocusableEl) {
firstFocusableEl.focus();
e.preventDefault();
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment