I tried using accesskey in Angular 6. but it seems does not work.
Component html tamplate snippet:
<input id="search_value" accesskey="S">
Can anyone provide working code example in Angular 6. Thanks in advance
I tried using accesskey in Angular 6. but it seems does not work.
Component html tamplate snippet:
<input id="search_value" accesskey="S">
Can anyone provide working code example in Angular 6. Thanks in advance
Your code works, provided the 'S' is lowercase. accesskey
has different keyboard shortcuts per browser and OS: in your example on Windows and Chrome, pressing [Alt] + [s]
would focus the element.
If you need a different shortcut combo, you'll need to listen for the key press. This can be done in plain JS fairly simply, i.e in this example.
However, the 'Angular' way means doing it without interacting with the DOM directly. This would be accomplished via injecting the Renderer2
and setting up the event listener that way:
constructor(private _r: Renderer2) {}
ngOnInit() {
this._r.listen(document, 'keyup', (event) => {
if(event.keyCode === 83) {
// assuming you get a reference to the input element
this.input.nativeElement.click();
}
})
}
Even better, with Observables:
ngOnInit() {
Observable.fromEvent(document, 'keyup').pipe(
filter(s => s.keyCode === 83)
).subscribe(s => this.doStuff())
}
This could easily be wrapped up in a directive as well.
Best I can tell, there is no 'Angular Approved' way to manually change the focus of elements. Of course you can always do it by accessing nativeElement with ElementRef, and then calling the DOM method '.focus()', but Angular provides no built-in way to do this (they even removed the 'invokeElementMethod' functionality that was in Renderer from Renderer2). You can bind to the 'tabindex' attribute of an input which at least lets you define the order that the tab key will focus them in, but other than that I don't think you can change focus with any angular approved methods. To do what you are asking, I think you'd have to use HostListener or some other way of setting up a keyup/keydown listener, listen for the specific key you are interested in, and then set focus manually using the DOM '.focus()' method.