Using ViewChild in Angular 4 to set focus on dynamically generated textboxes

Below is an example of a dynamically generated textbox:

<tr *ngFor="let item of data; let in=index">
    <td>
                        <input #unitNumber type="text" name="workPerformed-workcode-{{in}}" [(ngModel)] = "item.unitnumber" >
                      </td>
<td> <!-- Search option is given to choose the unit number----></td>
</tr>

A search option is provided to select the unit number. When a unit number is chosen, the corresponding textbox will be focused using ViewChild.

This is my attempt:

@ViewChildren('unitNumber') enteredUnitNumbers;

// To initiate searching, I utilized a material dialog box
const dialogRef = this.dialog.open(SearchEquipmentComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(
      <!-- HERE I NEED TO DO THE FOCUS ON PARTICULAR TEXTBOX ---->
     // console.log(this.enteredUnitNumbers.toArray().map(x => x))
});

The console log above shows undefined. My objective is to focus on the specific unit number textbox once the dialog box is closed.

Please provide solutions.

Answer №1

This code snippet should achieve the desired outcome:

enteredUnitNumbers.toArray()[0].nativeElement.focus();

To target a specific input, make sure to replace the 0 with the index of that input.

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 method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

Exploring Angular's Observables for handling HTTP requests

Exploring Angular Observable Documentation As I delved into the Angular observable documentation mentioned above, I came across a section that compares promises with observables. Observables provide many values, while promises provide one. This characte ...

Difficulty encountered when attempting to connect Angular 2 with a Custom Web API through asp.net MVC 5 Web API

I am encountering an issue when trying to call a Custom Web Api in ASP.NET MVC 5. Below is the code for my Web Api Controller and Angular JS 2. [Route("api/email/detail/{id:int}"), HttpGet] public async Task<IHttpActionResult> EmailDetail(int id) ...

Managing file imports in Angular 2+ Unit Testing

Within my project, there are various utility functions that handle data transformations and other tasks. These functions are not contained within a class and are utilized across multiple utility files. Being relatively new to angular testing, I've sp ...

Is it feasible to replicate an error in TypeScript with certain modifications?

Currently, I'm facing a challenge where I need to utilize Sentry.captureException with an error that I have received. However, before doing so, I am attempting to modify the error message. Despite spending considerable time searching for a solution, I ...

`The term 'promise' is typically used to describe a type, yet in this context, it is being utilized as a value.`

I attempted to employ a promise for an Async call in my custom form validator, so I created a separate TypeScript file called usernameValidators.ts. import { Control } from 'angular2/common'; export class UsernameValidators { static should ...

The application encountered an issue where it was unable to access the property 'stateName' of an undefined value

My requirement is to display data from a table inside a modal when a specific row is clicked. I am able to retrieve the text box value but not the dropdown value, which shows up in the console window on the right side of figure 2. https://i.sstatic.net/eOT ...

If the boolean value is false, the material icon set will be colored red

My task management application requires a thumbs up/down icon to be displayed in green or red based on whether the task is completed or not. Previously, I was able to achieve this by using ngClass and applying different CSS classes to the icon. HTML: < ...

Tips for efficiently reusing validation rules across multiple endpoints in Express Validator

In order to streamline my coding process, I am interested in finding a way to reuse Express Validator schemas across multiple endpoints. Rather than creating separate schemas for each endpoint (such as POST and PUT requests), I would like to have a singl ...

Are there any Android applications specifically designed for editing Typescript files?

While this may not be a typical programming inquiry, I have phrased it in a binary manner in hopes of meeting the criteria. I have been utilizing Quoda on my Android device and have encountered the need to edit .ts / Typescript files, which the app does n ...

Out of the blue, I encountered an issue while trying to install Express in node.js using Types

Encountered a failure while attempting to install Express with node.js in Typescript. Received the following warning: https://i.sstatic.net/XcrGX.png Performed npm initialization, started index.js, created tsconfig.json, and installed ts-node. The comman ...

In Typescript, you can build ultra-strict type definitions for your

If I define a custom type like this: type SmallCapsString = string And then utilize it in a function as shown below: function displaySmallCapsString(input: SmallCapsString) { ... } displaySmallCapsString('UPPERCASE') The code above compiles ...

Interpretation of a text/xml response from API call as an application/pdf document

I have a backend Spring Boot 2 application deployed on Azure Web App. It communicates with an Angular frontend deployed on Azure Static Web App. The backend generates a PDF file which is sent as byte[] with the 'application/pdf' header. The front ...

What steps do I need to take to deploy an Angular 4, instead of Angular 2, application on IIS

Despite numerous attempts, I struggled to run a simple "Hello world" application in Angular 4 on IIS. All my efforts resulted in a blank page with no errors. The only successful methods I found were: 1- Building the application using the "ng build" CLI ...

Advanced Layout: Angular Event window:scroll not Triggering

One issue I am facing is that the event gets triggered on some components but not others. For example, it fires as soon as I route to all other components except for the Landing component. Below are my code snippets: <-- Main Component --> <div c ...

No issues with TypeScript when referencing an undefined global variable within a function

My journey with typescript has just begun. I had the impression that it was designed to catch mistakes like this, but perhaps my understanding is lacking. The issue arises when attempting something similar to the following: interface A { prop: string } ...

Angular Bootstrap dropdown menu opens on the left side for items

When using ngbDropdown, the default alignment of drop down items is on the right side. However, if the drop down alignment is too far to the right, the item may become invisible. Below is the HTML code: <div ngbDropdown class="d-inline-block float_rig ...

Guide on properly setting up and configuring Cypress while using a proxy

After downloading the Cypress zip file and extracting it, I proceeded to run the npm installation command from within the e2e folder of my Angular project: npm install /path_to_cypress_folder/cypress/Cypress/resources/app The installation was successful a ...

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

How to manually remove an Angular directive

Is it possible to manually remove a directive? For instance, if I need the directive to perform a task once and then be cleared from memory. @Directive({ selector: '[doSomething]' }) export class DoSomethingDirective { constructor(private ...