(the code presented is in TypeScript and I'm working with Angular 5, but I don't think that's the issue, so prove me wrong!)
I have a basic input field that triggers events in an Angular component.
(EDIT: I've added the complete component code below)
<span class="__picker-container">
<input type="text" #geoSearchBox (keypress)="keyPress($event)" (keyup)="searchTerms.next($event)" [placeholder]="placeholder" />
<small *ngIf="isLoading">Loading...</small>
<div #pickerList class="__picker-list">
<a href="javascript:;" *ngFor="let result of searchResults | async" (click)="select(result.id)">{{ result.name }} ({{ result.code }})</a>
</div>
</span>
While keyup
conducts a simple rest search to display results in a sibling UL
, keypress
is used to detect specific keyboard inputs while typing.
In this case, it checks for keyDown
and keyUp
to navigate through the results. Here is the relevant code:
keyPress(event: KeyboardEvent) {
const pl = <HTMLDivElement>this.pickerList.nativeElement;
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
if (pl.childElementCount > 0) {
if (event.key === 'ArrowDown') {
this.childNodeIndex = this.childNodeIndex++ < pl.childElementCount - 1 ? this.childNodeIndex++ : 0;
} else if (event.key === 'ArrowUp') {
this.childNodeIndex = this.childNodeIndex - 1 >= 0 ? this.childNodeIndex - 1 : pl.childElementCount - 1;
}
console.log(this.childNodeIndex);
(<HTMLElement>pl.children[this.childNodeIndex]).focus();
}
}
}
Everything seems straightforward so far.
Now, here comes the odd behavior: after calling focus()
, the element is correctly focused, but then the execution gets stuck as other keypress events are ignored.
If I remove the line
(<HTMLElement>pl.children[this.childNodeIndex]).focus();
the console log shows the correct values for each keystroke sent.
What could be causing this issue in the code?
Thanks in advance, Valerio