When HTMLElement focus is activated, it interrupts the flow of execution

(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

Answer №1

When you specify the <a href="..."> as the focus, it becomes the element that will capture keyboard events instead of the <input>.

To resolve this issue, make sure to add the event handlers to the <a href="..."> as well.

<a href="javascript:;" *ngFor="let item of listOfItems | async" (click)="select(item.id)"
    (keypress)="keyPress($event)" (keyup)="searchTerms.next($event)"
    >{{ item.name }} ({{ item.code }})</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most efficient method for validating an exception in Protractor?

In recent code reviews within our team, a discussion arose about writing tests that assert on expected exceptions. While this is correct, the method used involved a try/catch block, which some believe may not be the most performant approach. This raises th ...

Display the div only if the router is not the same in angular 2

If the router is not equal to an empty string or '/dashboard', I would like to display the following code: <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right> & ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

Accessing form validation status of page 1 in Angular2 from page 2 - A simple guide

My current project utilizes Angular 4.2.x with two main pages: page 1 containing a form and page 2 serving as a summary page. Upon successful validation of all fields on page 1, I update a boolean flag in a shared service between the two pages. The expect ...

Concerning the utilization of the <mat-toolbar> element within Angular

Is the mat-toolbar in Angular going to persist across all components and pages of the application? Will it be present in every component throughout the application? <mat-toolbar color="primary"> <mat-toolbar-row> <span>Welcome to C ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

I am experiencing a strange situation in node.js where the `then` condition of a Promise is not being executed as expected

I am currently troubleshooting a Promise scenario and I am puzzled as to why the second then condition is failing to execute in the setup method. In my app.js code, I can see that the initialize() function is being called and it properly awaits the complet ...

"Elaborate" Typescript Conditional Generic Types

Scenario I am currently working on implementing strong typing for the onChange function of a UI library's Select component. To provide some context, the existing type definition for their onChange is as follows: onChange?: (...args: any[]) => v ...

What is the best way to navigate back to the previous page while retaining parameters?

Is there a way to return to the previous page with specific parameters in mind? Any suggestions on how to achieve this? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } What I am looking ...

Resolve ESLint errors in _document.tsx file of next.js caused by Document<any> and ctx.renderPage = () with TypeScript usage

maxbause took the initiative to create a comprehensive boilerplate project for Next.js, complete with GraphQL and styled components in TypeScript. Check out the project here However, upon integrating ESLint into the project, I encountered several warning ...

Issue with displaying children in Angular 2 router: children components not appearing on the

I am currently in the process of incorporating a user authentication bundle into my Angular 2 project by following this tutorial at . I have organized all the files from the bundle into a parent folder named "loginMGR", and modified the module, components ...

Angular: Intercept Drag and Drop Actions

I am utilizing angular-ui to create a sortable list using "drag and drop" functionality, and it is functioning perfectly. Here is an example of how it works: index.html <ul ui-sortable ng-model="list"> <li ng-repeat="item in list" class="it ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

Angular jsonp.get request was denied despite receiving a status code of 200 indicating success

I have been attempting to access my basic web API created in Jersey, which returns the following data: [ { "id": 1, "name": "Facebook", "userName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4 ...

Implement ExpressTS on vercel platform

I have recently developed an Express TypeScript project on GitHub and now I am attempting to deploy it to Vercel. The folder structure of the project is as follows, with 'dist' containing app.js and 'src' containing app.ts. dist dto mi ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Retrieving Information from a JSON Object using Angular 2

I'm dealing with a JSON object response. The object looks like this: {auth_token: "60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45"} auth_token:"60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45" proto : Object My goal is to extract the value "60a483bc0b1bc4dc0231f ...

Angular Materials auto-complete - Presenting choices depending on certain criteria

I have implemented 4 components, each containing a material autocomplete feature with the same set of options. Whenever I select an option in one component, it sets isAvailable to false and disables that option in the other components. The array below show ...