I'm desperately trying to figure out the best way to add focus trap to my modals in an Angular 8 application. I've stumbled upon the Angular Material CDK and installed it for the A11y Accessibility tools only but I can't figure out how to import and use FocusTrap
or FocusTrapFactory
.
If I try to add either to my declarations
or imports
arrays in @NgModule
I get errors. Installing them in the providers
does nothing. There's nothing I see in the docs on how to specifically pull the tools in to use. I have cdkTrapFocus
, cdkFocusRegionStart
, cdkFocusInitial
and cdkFocusRegionEnd
all setup in a modal to test. I've tried just pulling in FocusTrap
and FocusTrapFactory
into my component only, but still nothing.
https://v8.material.angular.io/cdk/a11y/overview#focuskeymanager
Has anyone successfully gotten this to work? If I have to use the Material UI tools to get this to work I will need to find another solution for trapping focus in my modals.
My modal component is a simple wrapper I open and close by ID with a service. It's basically just like: https://jasonwatmore.com/post/2019/07/12/angular-8-custom-modal-window-dialog-box
All you need to do is import the a11y module from cdk in your module
import { A11yModule } from '@angular/cdk/a11y';
imports: [
A11yModule
]
Add the focus trap directives to the parent element of your dialog contents e.g. below is a snippet where the dialog contents are projected
<div class="modal-content" cdkTrapFocus [cdkTrapFocusAutoCapture]="true">
<ng-template *ngTemplateOutlet="contentsTmpl"></ng-template>
</div>
so long as the angular injected dom elements are enclosing the modal contents it should work. https://jasonwatmore.com/post/2019/07/12/angular-8-custom-modal-window-dialog-box example has an issue.
The modal created in this example is always there in dom and cdk auto focus capture traps focus when element is created or destroyed!
I modified this example a bit and it works fine. Here is the modified example
https://stackblitz.com/edit/angular-8-custom-modal-dialog-focustrap?file=src/app/_modal/modal.component.html
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