Navigate to the next input on the p-table when entering a value

In my component, I have a p-table with input fields. I want to achieve the functionality where, after filling in the input and sending the data to the database via REST, pressing 'tab' will shift the focus to the next input field similar to Excel.

Should I implement this using directives?

<ng-template pTemplate="body" class="tableBody" let-rowData let-x="rowIndex" let-columns="columns">
   <tr [pSelectableRow]="rowData" [ngClass]="rowData.editable != 'true' ? 'cell-color-gray2' : null" [hidden]="!showSubTotal(rowData)">
      <td *ngFor="let col of columns; let i = index" class="ui-resizable-column" [pEditableColumn]="rowData[col.field]" [pEditableColumnField]="rowData[col.field]">
         <p-cellEditor>
            <ng-template pTemplate="input">
               <div *ngIf="menuLabels.state=='editable' && rowData.editable=='true'">
                  <div *ngIf="col.field=='customEffort'" class="tableColumnRight">
                     <input #inputs type="text" ngDefaultControl [(ngModel)]="this.rowData.effort" autoResize="autoResize"
                            (focusout)="workaroundUpdateDataEffort({ data: rowData, costCenterNr: col.header.split(' ')[0], columns: columns }, x, i)"
                            (keydown.tab)="workaroundUpdateDataEffort({ data: rowData, costCenterNr: col.header.split(' ')[0], columns: columns }, x, i)"
                            (keydown.enter)="workaroundUpdateDataEffort({ data: rowData, costCenterNr: col.header.split(' ')[0] })"
                            (keydown.esc)="workaroundCatchEsc({ data: rowData })">
                  </div>

Answer №1

If you want to focus on a specific HTML element, there are different ways to achieve it. One way is through using a directive, but you can also trigger the focus action through an event. The key is having a reference to the HTML element that you want to focus on. This can be accomplished by utilizing a ViewChild in your component:

@ViewChild('tab') inputEl:ElementRef;

To make this work, you need to define a ref-id in your HTML markup:

<tr #tab> <!-- element that holds the loop -->

Then, when you call a REST service in your code:

onYourEvent(index) {
  restService.sendData().subscribe((res) => {
    // handle the received data
    // then proceed to set focus to the next element:
    const inputs = this.inputEl.nativeElement.querySelectorAll('input');
    if (inputs.length > index + 1) {
      inputs[index + 1].focus();
    }
  });
}

For a demonstration, you can check out this demo on stackblitz

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

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

The value of the local variable remained unchanged despite the occurrence of global events (window.onresize)

The value of the local variable remained unchanged despite global events (window.onresize) occurring. export class TestComponent implements OnInit { a: number = 0; b: number = 0; ngOnInit() { window.onresize = () => { ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

Tips for setting an argument with a promise data type

I am currently working on writing unit tests using jest to test two functions in a separate file called generator, where I generate fake data : generator.ts export async function generateReportData(overide = {}) { return { clientId: faker.data ...

Unable to simulate the Enter key press event for a text area using Angular 7

I've implemented a feature that allows users to type something and then press the submit button, at which point the cursor should move to the next line. If the user types some words and presses the Enter key, the cursor should also shift to the next l ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

Error encountered when attempting to inject a service into another service due to circular dependency issues

I have encountered an issue while working on my Angular 5 application where I am facing errors when trying to inject one service into another service. Below is a snippet of the DataService: import { Injectable } from '@angular/core'; import { H ...

Streamline copyright verification with Angular

We are currently working on an angular application that we plan to release as open-source. We make sure to include copyright information in every file, specifically in the .ts and .scss files. However, being human, there are times when we may forget to ad ...

Making sure that a commitment does not come to fruition

Perhaps this code snippet below functions correctly as it is, but I'm uncertain if it's the best approach to prevent potential runtime issues. Here's the code in question: const ep = `${environment.api.baseUrl}/login`; return this.http.pos ...

Designing Angular 1 table row components with future migration to Angular 2 in consideration

Issue with AngularJS nested directives placement outside parent element Encountering the same challenge in my project using Angular 1.4, but I am also aiming to construct the rows as Angular 2 components which prevents me from using "replace: true". I am ...

Navigate back to the initial page in Ionic2 using the navpop function

I have an application that needs to guide the user step by step. While I am aware of using navpop and navpush for navigating between pages, I am unsure about how to use navpop to go back to the first page. Currently, I am attempting to pop() twice if ther ...

In order to dismiss the popup message in the component.ts file within Angular 4, I must figure

Currently in my component.html, I have a popup message with opening and closing functionality implemented in html. However, I now need the close functionality to be moved to a method. <ng-template #content let-c="close" let-d="dismiss"> < ...

Using Angular 6 to pass basic authentication in httpClient's httpOptions

I am currently working on an Angular 6 service where I am attempting to modify a record, but the system is indicating that I do not have authorization. At this moment, my code looks like this: const httpOptions = { headers: new HttpHeaders({'Conte ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

Encountering a module resolve error when a tsx file is added to the project item group

After setting up an asp.net core project with a react template and configuring Typescript, I created a simple file named Test.tsx with the following code: import React from 'react'; class Test extends React.Component { render() { r ...

Angular 5's recursive directives in dynamic modules without any circular dependencies

I've been experimenting with loading dynamic templates into my Angular 5 app. My first attempt was following the examples in the official Angular documentation, but I quickly realized that they only cover loading static components dynamically. Next, ...

Utilizing Angular 2 Components in a Repetitive Manner

Within my parent component, I make two references to a child component: @Component({ selector:'cy-page-phone', template:` <cy-page-fileUploadEle></cy-page-fileUploadEle> <cy-page-fileUploadEle></cy-pa ...

Inquiring about the syntax of TypeScript and React – any insights?

Hello! I am currently delving into the world of React and Typescript, and I have a query regarding syntax interpretation. Let's say I have a segment of code from test.tsx shown below. // prop is defined somewhere over here. private displa ...

Exploring the world of Wordpress Rest API for retrieving posts

I'm attempting to display all of my posts from my WordPress website. Currently, there are 2 posts available which can be viewed in the JSON file: View export class HomePage { url: string = ‘http://feederhorgasz.000webhostapp.com/wp-json/wp/v2/posts ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...