Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, how to block the keyboard interaction with the parent component

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?

like image 495
Ricardo Avatar asked Mar 15 '18 15:03

Ricardo


2 Answers

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>

like image 78
funkizer Avatar answered Oct 27 '22 01:10

funkizer


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.)


A note on accessibility

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.

like image 37
Zze Avatar answered Oct 26 '22 23:10

Zze