Utilizing Keyboard Events within the subscribe function of ViewChildren to focus on typing in Angular2 TypeScript

Is there a way to trigger a Keyboard Event on subscribe in ViewChildren used within a button dropdown nested ul li?

<!-- language: lang-js -->

import { Component, ElementRef, Renderer,ViewChildren,QueryList,AfterViewInit,OnChanges} from '@angular/core';
import {HttpCarService} from './service/vservice';
import {Request} from './model/locationrequest.model';
import {Location} from './model/location.model';

@Component({
    selector: 'my-app',
    templateUrl: '/app/view/loc.html',
    providers: [HttpCarService]
})
export class AppComponent implements AfterViewInit, OnChanges{

public result: string;
public result1: Location[];
public result2: Location[];
public result3: Location[];
public check: boolean;
@ViewChildren('seidropdown')
 seidr: QueryList<Location>;
 key: KeyboardEvent;

selectedLCItem = 'Select an Item';
public isLocationContextSelected: Boolean;

setFocus(renderer:Renderer){
  this._renderer.invokeElementMethod(
                this.element.nativeElement, 'focus', []);
            return;                 
}

ngAfterViewInit(){
 this.seidr.changes.subscribe((KeyboardEvent.bind(this.setFocus(this._renderer),this.result1)));
}
ngOnChanges(){
}        

constructor(httpCarService: HttpCarService, element: ElementRef, public _renderer: Renderer) {
    let request = new Request(false, false, true, true, true, true);

    httpCarService.getCarsRestful1(request).subscribe(data => this.result1 = data,
        err => console.log('ERROR!!!'),
        () => console.log('Got response from API', this.result1)
    );

    this.element = element;
}

processSelectedContext(item: string) {
    this.selectedLCItem = item;
    this.isLocationContextSelected = true;
}

public element: ElementRef;

public inputEvent(e: KeyboardEvent, isUpMode: boolean = false): void {
    let index = 0;

    alert('Slice value:' + this.result1.length);
    console.log('Key Value' + e.key);
    this.seidr.changes.subscribe(e.currentTarget.addEventListener(this.setFocus()));
  this.setFocus(this._renderer);
}

public inputEvent1(e: KeyboardEvent, isUpMode: boolean = false): void {
    let index = 0;

    let e1 = this.element.nativeElement.getElementsByTagName('a');
    for (index = 0; index < e1.length; index++) {
        let a1 = e1[index].innerHTML.charCodeAt(0);
        let a2 = e1[index].innerHTML.charCodeAt(1);
        let a3 = e1[index].innerHTML.charCodeAt(6);
        let a4 = e1[index].innerHTML.charCodeAt(50);

        while (e.keyCode === a1) {
            this._renderer.invokeElementMethod(
                e1[index], 'focus', []);
            return;
        }
        while (e.keyCode === a2) {
            this._renderer.invokeElementMethod(
                e1[index], 'focus', []);
            return;
        }
        while (e.keyCode === a3) {
            this._renderer.invokeElementMethod(
                e1[index], 'focus', []);
            return;
        }
        while (e.keyCode === a4) {
            this._renderer.invokeElementMethod(
                e1[index], 'focus', []);
            return;
        }
    }
}
}

In this instance, keyboard focus event has been successfully implemented through direct DOM interaction by calling getElementBytag, which may introduce tight coupling in Angular 2.

Answer №1

Apologies for the delay in updating, but I wanted to share a solution that I came up with using a directive. Since it's not straightforward to access the nodelist of HTMLElement without elementRef, I utilized ng2-bootstrap to help implement the directive. Check out the directive here on GitHub

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

Resolving the Challenge of Disabling typescript-eslint/typedef in Angular 13 with ESlint

I started a fresh project in Angular 13 and configured typescript-eslint by running the command below: ng add @angular-eslint/schematic I made changes to my .eslintrc.json file where I disabled the rules for "typescript-eslint/typedef" and "typescript-esl ...

How can I effectively link data to an Angular Material dropdown in Angular 5?

Essentially, I am updating a user profile with user information that needs to be bound to the corresponding fields. this.editOfferprice= new FormGroup({ xyz : new FormControl(xxxx,[]), xxx: new FormControl(xxxx,[Validators.required]), ...

Defining a TypeScript interface specifically tailored for an object containing arrow functions

I encountered an issue while trying to define an interface for the structure outlined below: interface JSONRecord { [propName: string]: any; } type ReturnType = (id: string|number, field: string, record: JSONRecord) => string export const formatDicti ...

Are click events on nodes supported in Angular when using Mermaid.js?

I am currently working on integrating Mermaid flowchart drawing Javascript into my Angular 9 based client application. I have successfully created the flowchart diagram, but now I need to add a click event to a specific node with a function defined in Type ...

Sending data to bing map API headers

When calling the Bing Maps API, my code looks like this: var gcR = "https://dev.virtualearth.net/REST/v1/Locations?query=" + val + "&key=" + key; return this.http.get(gcR) .map((res: any) => { return res.json(); }).catch( ( ...

Encountered a RunTime Error when attempting to Lazy Load a module

When attempting to lazy-load a component separately, an unexpected run-time error is occurring. This issue is specifically related to writing loadChildren within the routing module of another component in Angular 6. Any assistance with resolving this error ...

`End Angular2 session and close browser tab`

Currently, I am developing a web application using Angular2. I am looking to include a button in the application that, when clicked, will not only close the application but also the browser tab where it was launched. I have been exploring various solution ...

How can I retrieve header values in the canActivate function in Angular?

Depending on the value of userRole received from the header, I need to redirect to different user pages. angular.routing.ts { path: '', pathMatch: 'full', redirectTo: '/login' }, { path: 'user', loadChildren: &apo ...

Issues arise when Angular is unable to establish a connection with the backend server written in Golang

Using nginx to serve angular (index.html) is working fine. However, I keep encountering errors when attempting to communicate with my backend. Dockerfile Setup for NGINX + Angular FROM node:12-alpine as builder WORKDIR /usr/src/app COPY . . RUN npm instal ...

Using Jest and Typescript to mock a constant within a function

Just getting started with Jest and have a question: Let's say I have a function that includes a const set to a specific type (newArtist): export class myTestClass { async map(document: string) { const artist: newArtist = document.metadat ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...

There seems to be an issue with the response type in the node.js environment

I am currently working on node.js and typescript, but I am encountering a minor issue. Below is the routeController I have created: public allUsers = (req: Request, res: Response) => { res.status(500).json({ status: "ERROR", ...

What is the correct location to import a custom theme in MUI for Next.js?

I am currently working on a React/Next.js project and I need to customize the colors using MUI. After discovering createTheme(), I realized that the project is written in Typescript. Should I create a separate file with the following code? And where shou ...

Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this: Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either tr ...

Is there a way to define the length of children when performing props type checking?

I need my component to only allow for three children that are considered as type React.ReactChild. However, I'm uncertain if ReactChild is the most suitable type to validate. Essentially, these children should be three distinct sections. function Top ...

Upon initial loading, the default sidenav in Angular is not selected

I need to ensure that the sidenav loads the basic page during the initial load. This is controlled by the routing.ts file shown below: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; i ...

The Angular Validator Pattern may be effective in HTML, but it seems to encounter limitations when

In the world of HTML, Regular Expressions can be quite useful as demonstrated in the example below: <input type="text" formControlName="mgmtIP" class="input-text" pattern="([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]& ...

Creating nested Angular components with Parent/Child connections

I am currently working on wrapping some third-party components within my own Angular 5 components Before wrapping these components, the code looked like this: <div> <xyz-menubar> <a xyzMenubarItem></a> <a xyzMenubarIt ...

Incorporating a redirect link into a button within an AlertController

(Angular & Ionic) Is it possible to include a link to the Play Store in my alert controller modal? const alert = this.alrtCrtl.create({ title: `...`, subTitle: `...`, message: `<div class="image-container"> <img i ...

Keep the entered value in storage as a helpful clue

Currently, I am working with angular 4 and have developed a form that is functioning correctly. However, I have encountered an issue where entering input into a text box displays the last value that was entered in that field. For example, if I input the ...