core/common/dropdown-focus-trap.directive.ts
Directive to manage focus trapping and keyboard navigation for ngx-bootstrap dropdowns with container="body".
When a dropdown is appended to the body using container="body", the standard cdkTrapFocus
directive doesn't work because the dropdown content is outside the normal DOM hierarchy where
the directive is applied.
This directive:
container="body" opensSimply apply this directive to the same element that has the dropdown directive:
<div dropdown container="body" c8yDropdownFocusTrap #myDropdown="bs-dropdown">
<button dropdownToggle>Select option</button>
<div *dropdownMenu class="dropdown-menu">
<c8y-list-group role="list">
<c8y-li tabindex="0" role="listitem">Option 1</c8y-li>
<c8y-li tabindex="0" role="listitem">Option 2</c8y-li>
</c8y-list-group>
</div>
</div>See CDK FocusTrap
<b>Example :</b><div><pre class="line-numbers"><code class="language-html"><div dropdown container="body" c8yDropdownFocusTrap #myDropdown="bs-dropdown">
<button dropdownToggle>Select option</button>
<div *dropdownMenu class="dropdown-menu">
<c8y-list-group role="list">
<c8y-li tabindex="0" role="listitem">Option 1</c8y-li>
<c8y-li tabindex="0" role="listitem">Option 2</c8y-li>
</c8y-list-group>
</div>
</div></code></pre></div><h2>Features</h2>
<ul>
<li><strong>Focus trapping</strong>: Tab key navigation cycles through dropdown items</li>
<li><strong>Automatic focus management</strong>: Enter/Space automatically closes dropdown and returns focus to toggle button</li>
<li><strong>ESC key isolation</strong>: Pressing ESC closes only the dropdown, not parent modals/drawers, and restores focus</li>
<li><strong>Form-friendly</strong>: Skips automatic close for inputs, textareas, and selects within the dropdown</li>
<li><strong>Automatic cleanup</strong>: All listeners and focus trap removed when dropdown closes</li>
<li><strong>Zero configuration</strong>: Just add the directive, no manual focus management needed</li>
</ul>
| Selector | [c8yDropdownFocusTrap] |