Angular: Trap focus with in a block
trapFocus directive
Published in
1 min readJul 7, 2020
This is how to instruction of building a directive which trap focus within a block, for example, not leaving dialog until it’s closed.
Steps
- Create
TrapFocusDirective
- Use it.
1. Create TrapFocusDirective
The principle for it is simple
- When
Shift-Tab
pressed on the first element, focus the last element. - When
Tab
pressed on the last element, focus the first element.
2. Use It.
In your module, e.g., app.module.ts
import { TrapFocusDirective } from './trap-focus.directive';@NgModule({
imports: [ ... ],
declarations: [ ..., TrapFocusDirective ],
..
});
export class AppModule { }
In your html, e.g., app.component.html
<fieldset trapFocus >
.....
</fieldset>