简体   繁体   English

Angular,如何阻止键盘与父组件的交互

[英]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? 我该如何防止这种行为?

Angular CDK provides a directive called cdkTrapFocus which prevents focus moving outside a dom node and it's children. Angular CDK提供了一个名为cdkTrapFocus的指令,它可以防止焦点移动到dom节点和它的子节点之外。 They use this in MatDialog, and it works great. 他们在MatDialog中使用它,效果很好。

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 如果您不想切换到使用MatDialog,或者您需要在对话框之外的其他布局中使用它,您可能需要考虑使用cdkTrapFocus: 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> 它应该像导入和声明指令一样简单,然后是<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.) 这将完全阻止使用页面上的箭头键以及Tab键(目标之间的标签)。


A note on accessibility 关于可访问性的说明

One of the comments from @Ricardo states that this is a very poor approach for accessibility. @Ricardo的评论之一表明,这是一种非常糟糕的可访问性方法。 I think it is important to remember that many people with accessibility issues will use a program like Jaws to navigate a web page. 我认为重要的是要记住,许多具有可访问性问题的人将使用像Jaws这样的程序来浏览网页。 These programs capture the keystrokes outside of the web app and then propogate these actions through to the browser. 这些程序捕获Web应用程序之外的击键,然后将这些操作传播到浏览器。 Blocking keydown events will not inhibit this - JAWS specifically transmutes the users keydown events into focus events. 阻止keydown事件不会抑制这种情况 - JAWS专门将用户keydown事件转换为焦点事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM