The environment
I have a big component tree on my angular application with multiples routes outlet to display specific component on each level. the deepest level is a modal that manages certain info.
The Problem
I can block the interaction through the mouse from my child component to the parent component event if you can see it (the parent component ) but when I use the keyboard I'm able to navigate to the parent component and select options in all my parent component
the question
How can I prevent this behavior?
Angular CDK provides a directive called cdkTrapFocus which prevents focus moving outside a dom node and it's children. They use this in MatDialog, and it works great.
If you don't want to switch to using MatDialog or you need this in some other layout than a dialog, you might want to look into using cdkTrapFocus on it's own: https://github.com/angular/material2/blob/3aceb7361cc34ad987f7b1ca39339d3203248341/src/cdk/a11y/focus-trap/focus-trap.ts#L340
It should be as simple as importing and declaring the directive, then <div cdkTrapFocus></div>
Well you could implement some crude event binding like this:
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
// tab, up, down, left, right
if (e.keyCode == '9' || e.keyCode == '38' || e.keyCode == '40' || e.keyCode == '37' || e.keyCode == '39') {
console.log("prevent");
e.stopImmediatePropagation();
e.preventDefault();
}
}
This will completely prevent use of the arrow keys on the page, as well as the tab key (tabbing between targets.)
One of the comments from @Ricardo states that this is a very poor approach for accessibility. I think it is important to remember that many people with accessibility issues will use a program like Jaws to navigate a web page. These programs capture the keystrokes outside of the web app and then propogate these actions through to the browser. Blocking keydown events will not inhibit this - JAWS specifically transmutes the users keydown events into focus events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With