Trapping Focus with Angular CDK | Task

Ole Ersoy
May - 14  -  1 min

Scenario

We have three buttons within a section and we want the third button to receive the initial focus. and subsequently we want to keep focus in the section as the user tabs around to the different buttons.

Approach

First add the Angular CDK A11yModule to the application imports.

@NgModule({
imports: [BrowserModule, FormsModule, A11yModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})

Next markup the the section with the directive cdkTrapFocus and mark up Button 3 with cdkFocusRegionStart. When the section is focused the Button 3 button will receive focus first upon navigation within the section.

<h1>CDK Trap Section with Focus Regions</h1>
<section cdkTrapFocus>
<button>Button 1</button>
<button>Button 2</button>
<button cdkFocusRegionStart>Button 3</button>
<button>Button 4</button>
<button>Button 5</button>
</section>

Related Concepts

Angular CDK A11y Dcoumentation

Demo