0
0
Angularframework~30 mins

Keyboard navigation support in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Keyboard navigation support
📖 Scenario: You are building a simple Angular component that displays a list of items. You want to make sure users can navigate the list using the keyboard for better accessibility.
🎯 Goal: Create an Angular standalone component that renders a list of three items. Add keyboard navigation support so users can move focus up and down the list using the arrow keys.
📋 What You'll Learn
Create a standalone Angular component named KeyboardNavComponent.
Use a signal to track the currently focused item index.
Render a list of three items: Item 1, Item 2, and Item 3.
Add keyboard event handling to move focus up and down with arrow keys.
Use the *ngFor directive to render the list items.
Add tabindex attributes to make items focusable.
Ensure the focused item has a visible outline for accessibility.
💡 Why This Matters
🌍 Real World
Keyboard navigation is essential for accessibility in web apps. Users who cannot use a mouse rely on keyboard controls to interact with lists, menus, and other UI elements.
💼 Career
Many frontend developer roles require knowledge of accessibility best practices, including keyboard navigation support in Angular applications.
Progress0 / 4 steps
1
Create the list data
Create a standalone Angular component named KeyboardNavComponent. Inside the component, create a readonly signal called items that holds an array with the strings 'Item 1', 'Item 2', and 'Item 3'.
Angular
Need a hint?

Use signal from @angular/core to create a reactive array named items.

2
Add focused index signal
Inside the KeyboardNavComponent, add a signal named focusedIndex initialized to 0. This will track which item is currently focused.
Angular
Need a hint?

Use signal(0) to create a reactive number named focusedIndex.

3
Render list with keyboard navigation
Update the component template to render a <ul> with a *ngFor directive over items(). For each item, render a <li> with tabindex set to 0 if the index equals focusedIndex(), otherwise -1. Add a (keydown) event handler on the <ul> that calls a method onKeydown($event).
Angular
Need a hint?

Use *ngFor to loop over items(). Use [attr.tabindex] to set focusable attribute. Add (keydown) event on <ul>.

4
Implement keyboard navigation logic
Complete the onKeydown(event: KeyboardEvent) method to update focusedIndex when the user presses the ArrowDown or ArrowUp keys. Increase focusedIndex by 1 on ArrowDown unless at the last item, and decrease by 1 on ArrowUp unless at the first item. Use event.preventDefault() to stop page scrolling.
Angular
Need a hint?

Check event.key for 'ArrowDown' and 'ArrowUp'. Use this.focusedIndex.set() to update the focused index.