Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created July 7, 2020 19:04
Show Gist options
  • Save allenhwkim/6b279cf85c4343d6ba0ae79b67a4e774 to your computer and use it in GitHub Desktop.
Save allenhwkim/6b279cf85c4343d6ba0ae79b67a4e774 to your computer and use it in GitHub Desktop.
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) {
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];
element.addEventListener('keydown', function(e) {
var isTabPressed = e.keyCode === 9; // isTabPressed
if (!isTabPressed) return;
if ( e.shiftKey ) /* shift + tab */ {
if (document.activeElement === firstFocusableEl) {
lastFocusableEl.focus();
e.preventDefault();
}
} else /* tab */ {
if (document.activeElement === lastFocusableEl) {
firstFocusableEl.focus();
e.preventDefault();
}
}
});
}
}
@ishanjaidka
Copy link

Hi,
Having trouble with this directive when using it in the ngx-bootstrap (V6.2.0) modal.
Due to this directive there is Error: Maximum call stack size exceeded in Angular V10 when imported in another library when not using IVY.

Any idea on how this can be tackled?

TIA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment