Angular: Trap focus with in a block

trapFocus directive

Allen Kim
Digital-Heart

--

Photo by me_13 on Unsplash

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

  1. Create TrapFocusDirective
  2. Use it.

1. Create TrapFocusDirective

The principle for it is simple

  1. When Shift-Tab pressed on the first element, focus the last element.
  2. 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>

--

--