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

Modal for Firestore CRUD operations update()

Currently seeking assistance with a CRUD system that involves modal dialogues. I have successfully implemented adding and deleting functionalities, but I am encountering an issue with editing. Although I can retrieve the data for each record in its respect ...

"TypeORM's createConnection function on MacOS with PG database returns a Pending status even when using

Running MacOS Catalina version 10.15.4 To replicate the issue, follow these steps using the quick guide: npm install typeorm --save npm install reflect-metadata --save npm install @types/node --save npm install pg --save npm install typeorm -g typeorm in ...

What is the process for generating a new type that includes the optional keys of another type but makes them mandatory?

Imagine having a type like this: type Properties = { name: string age?: number city?: string } If you only want to create a type with age and city as required fields, you can do it like this: type RequiredFields = RequiredOptional<Propertie ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

Creating an eye-catching animation in Angular 2+ by applying a checkbox check effect to each checkbox dynamically generated within a loop

When I integrated a CSS animation for checkbox "cards" into an Angular project, the transition ceased to function properly. I have limited experience with Angular and am trying to work with existing code. While I managed to get a basic animation working wi ...

Using TypeScript to Manipulate SVG Polyline Shapes

In my TypeScript 3.1.1 project in VS Code with an Aurelia setup, I am facing a challenge while trying to manipulate an SVG Polyline using TypeScript code. The issue arises when attempting to create a new SVGPoint object. The initial HTML structure is as fo ...

The whereabouts of the node_modules folder during the development phase

As I dive into Angular 2 app development, I encountered an issue. Installing node modules in each project folder using npm install seems to be taking up a lot of disk space and causing duplication across multiple projects. This led me to consider creating ...

Develop a fresh category inspired by the properties of objects

Let's tackle the challenge of constructing a new type in Typescript based on an descriptive object named schema, which contains all the requirements expressed within it. Here is my proposed solution: type ConfigParameter<IdType, ValueType> = Re ...

Changing an element within an item stored in Ionic Storage

Hello, I am currently attempting to update a specific part of an object stored in Ionic storage. The current data in the Storage looks like this: key : object value : {a: "1", b: "2", c: "3"} To modify one of the values to 10, I created the following fu ...

Is it possible to host an Angular application on one port and a legacy application on another within a virtual machine?

I'm struggling to articulate this question properly, so please bear with me (or offer guidance) if I'm not doing it correctly. Here's the situation: In my Angular 4 app, the files are located on my host operating system (Ubuntu 16.04) and ...

Error: Platform core encountered a StaticInjectorError[t]: It is not possible to assign a value to the property '_injector', as it is undefined

This source code includes a rest API call and global variable reference. I have only utilized bootstrap CSS and omitted saving jQuery because bootstrap.js is not being used. After performing the (ng build -prod) command, I receive production build files ...

Retrieving class properties in typescript

I am working with a class that has numerous methods, which I refer to as myClass. When calling it, the syntax is as follows: myClass[key]() Is there a way to retrieve the valid values for key? I tried using keyof myClass, but received an error message st ...

The unspecified value of a dynamically generated button

Currently, I am working on generating ion cards with a response. Each ion-card contains 3 buttons. I am able to receive the response properly, but I am facing an issue with assigning values to the buttons, or possibly implementing it incorrectly. Here is ...

Unable to display image in Angular 4 even after selecting the checkbox

Currently delving into Angular 4 and facing a challenge. I am attempting to display an image when the checkbox is checked, however the functionality isn't working as expected. Below is how my app.component.html file is structured: <input type="che ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

Best practices for utilizing ngrx/store in Angular 2

As I am refactoring my Angular 2 applications to follow the ngrx pattern, some questions have arisen in my mind: My application retrieves a list of apps and a list of app categories. Can I manage state like "selectedCategory" (where only one can be select ...

Tips for utilizing ngModel within *ngFor alongside the index?

Currently, I am dynamically generating mat-inputs using *ngFor. My goal is to store each value of [(ngModel)] in a separate array (not the one used in *ngFor) based on the index of the *ngFor elements. Here's my implementation: <div *ngFor="let i ...

Troubleshooting AngularJS2 and npm in WebStorm and Chrome for Windows users

Having completed the official Hero tutorial for AngularJs2 using Visual Studio Code, I decided to switch my coding and debugging setup to WebStorm+Chrome on Windows 10. To achieve this transition, I took the following steps: Installed Chrome JetBrains ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

You can't access the values from one subscribe in Angular 2 within another subscribe (observable) block

Is there a way to properly handle the values from the subscribe method? I am facing an issue where I want to use this.internships in another subscribe method but it keeps returning undefined. Your assistance is greatly appreciated! Code: ngOnInit(): voi ...