Search code examples
angularrouterkeyboard-eventsangular-routerrouter-outlet

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?


Solution

  • 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>