How can I target and focus on a dynamically generated form in Angular 4/Ionic3?

One of the challenges I'm facing is dealing with dynamically created forms on a page. Each row consists of inputs and a button. Is there a way to select/focus on the input by clicking on the entire row (button)? It should be noted that the number of rows can reach up to 300 based on user input.

home.ts

export class HomePage {

      public homeForm: FormGroup;
      
      constructor(
        public navCtrl: NavController,
        public userData: UserDataProvider,
        private formBuilder: FormBuilder,
        public renderer: Renderer,
        public elementRef: ElementRef
      ) {

        this.homeForm = new FormGroup({
          bicos: new FormArray([
            new FormControl(null)
          ])
      });

       addInputs() {
          (<FormArray>this.homeForm.controls['bicos'])
          .push(new FormControl(null));
    }
}

home.html:

<form [formGroup]="homeForm"> 
    <ion-row formArrayName="bicos" *ngFor="let item of homeForm.controls.bicos.controls; let i = index" >
        <button id={{i}} ion-button clear style="color: black" class='hidden-button' (click) = "doSomething()">
    <ion-col align-self-center col-2>{{i+1}}</ion-col>
         <ion-col text-center align-self-center col-5>
           <ion-input type="text"></ion-input>
         </ion-col>
             <ion-col align-self-center col-5>400</ion-col>
         </button>
    </ion-row>
</form>

I have already explored different approaches, like using directives, but haven't found success yet.

Answer №1

If you want to reference inputs by index, you can utilize ViewChildren. Simply add the template ref #inputs to your input field:

<ion-input #inputs type="text"></ion-input>

To make this work in your component, remember to import ViewChildren and QueryList. Then, on your button click event where you invoke doSomething, pass the index and focus on that specific field based on the index:

<ion-row formArrayName="bicos" *ngFor="let item of homeForm.controls.bicos.controls; let i = index" >
  <button ion-button (click) = "doSomething(i)">
  <!-- ... -->

In your TypeScript file:

doSomething(index) {
  this.inputs.toArray()[index].setFocus();
}

Check out the StackBlitz example here!

Answer №2

I am currently working with Ionic 5 and have come up with a solution utilizing the input element's id.

Within the .html file:

<input id="input_{{ listItem?.id }}"> </input>

In the .ts file:

import { Renderer2 } from '@angular/core';

constructor(private renderer: Renderer2) 

When you need to focus on a specific input in the .ts file:

setTimeout(() => {
   this.renderer
    .selectRootElement(`#input_${listItem.id}`)
    .focus();
}, 1000);

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

Customize the width of the intl-tel-input field using Angular

Utilizing the Nebular ngx-admin template in my Angular application, along with ng2-tel-input for mobile number input. Below is the HTML code I am using: <div class="form-control-group"> <label class="label" for=" ...

Definition file for mapbox-gl-draw in Typescript, also known as d.ts file

I attempted to define the mapbox-gl-draw project in a typed manner but unfortunately, I was unsuccessful. Can anyone provide some guidance on this? Here is how the javascript file looks: 'use strict'; var Setup = require('./src/setup&apos ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

Is it feasible for the Drawer to be a fixed feature that sits atop the content?

I am looking to have a compact drawer positioned on the left side of my screen, similar to the example shown in the Material UI Documentation: https://i.sstatic.net/W21Kd.png However, I would like it to float over the content (like the variant="temporary ...

Maximize the benefits of using React with Typescript by utilizing assignable type for RefObject

I am currently working with React, Typescript, and Material UI. My goal is to pass a ref as a prop. Within WidgetDialog, I have the following: export interface WidgetDialogProps { .... ref?: React.RefObject<HTMLDivElement>; } .... <div d ...

Revamping elements according to ordered array. Angular version 4.3

Dealing with an array of data that needs to be sorted for displaying in a component seems to be a challenge. Despite having a functional code sample demonstrating the concept, the sorting is not reflected in the Angular app's DOM. The original data i ...

Developing a TypeScript frontend library

I am currently in the process of creating a frontend library consisting of React components and CSS/SCSS. Specifically, I am looking for: To build a single CommonJS .js file and .css file. To exclude external libraries (e.g. React) from the .js output. ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

Angular component experiencing issues with implementing Bootstrap styles

I followed a tutorial to apply the bootstrap 5.3.0 style to my navigation bar, but the outcome looks different from what was shown in the tutorial. This is the HTML code for the navigation component: <nav class="navbar navbar-default"> & ...

What is the reason behind the restriction on using 'this' on the left side of an assignment?

Within the component class, I've been working on this: export class myapp { detail; myarr = ['me', 'myself', 'i']; title = this.myarr[0]; this.detail = this.title ; //error } I'm curious why `this.detail` ...

I am excited to incorporate superagent into my TypeScript-enabled React project

Currently, I am attempting to integrate superagent into my TypeScript-ed React project. I have been following a tutorial on TypeScript with React and encountered some difficulties when using superagent for server requests, despite successfully utilizing ma ...

Choose between using Angular with either PHP and Python or with Django and Python in PHP

For my graduation project, I have developed the frontend using Angular and created a machine learning system with Python. Now, I need to integrate these two components by writing a Web API for Angular using Django, even though I have no prior experience wi ...

Using iframes in Angular 2/4's index.html

I'm currently working on an angular application and for session management, I've implemented OpenID Connect Session Management. I am attempting to inject iframes into the application. I need to include an iframe in my index.html as follows: < ...

What is the best way to incorporate the TUI image editor for Javascript into my Angular application?

Issue - I'm facing a challenge with my Angular application as I want to integrate Toast UI image editor. However, I am unsure about how to properly add the imports to app.module.ts in order to utilize it. Despite following the npm installation instru ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

How to use the Angular 7 CLI in a programmatic way

My goal is to set up a server that can launch an Angular 7 app. Another scenario where this capability would be useful is for more advanced generation tasks, such as adding multiple files directly after generating an Angular project. const angularClient = ...

A step-by-step guide on recovering information from a JSON file within Angular 12

Being a novice developer, I have taken on the challenge of creating a quiz application using Angular 12 to enhance my coding skills. However, I've hit a roadblock when it comes to retrieving data with questions and answers from a JSON file. Despite su ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

Using React and TypeScript to conditionally set props in a component

I am trying to assign a value to the component's prop when a variable is defined. Below you can find my current code. import Cropper from 'react-easy-crop' ... interface State { ... coverFile: File | null; ... } class Test extends React ...