Skip to content

Commit 69851f8

Browse files
feat(aio): focus search when / is pressed
This will aid accessibility. Closes #16129
1 parent 6dc6777 commit 69851f8

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

‎aio/src/app/search/search-box/search-box.component.spec.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ describe('SearchBoxComponent', () => {
5656
input.triggerEventHandler('keyup', { target: { value: 'some query' }, which: 27 });
5757
expect(search.search).not.toHaveBeenCalled();
5858
}));
59+
60+
it('should grab focus when the / key is pressed', () => {
61+
const input = fixture.debugElement.query(By.css('input'));
62+
window.document.dispatchEvent(new KeyboardEvent('keyup', { 'key': '/' }));
63+
expect(document.activeElement).toBe(input.nativeElement, 'Search box should be active element');
64+
});
5965
});
6066

6167
describe('on focus', () => {

‎aio/src/app/search/search-box/search-box.component.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
1+
import { Component, OnInit, ViewChild, ElementRef, HostListener } from '@angular/core';
22
import { SearchService } from 'app/search/search.service';
33
import { LocationService } from 'app/shared/location.service';
44

@@ -46,4 +46,11 @@ export class SearchBoxComponent implements OnInit {
4646
}
4747
this.searchService.search(query);
4848
}
49+
50+
@HostListener('document:keyup', ['$event'])
51+
onKeyUp($event: KeyboardEvent) {
52+
if ($event.key === '/') {
53+
this.searchBox.nativeElement.focus();
54+
}
55+
}
4956
}

0 commit comments

Comments
 (0)