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

Why does `window.location.reload()` only refresh the home page and not the other pages when using Angular?

After transitioning from the home page to the menu page, I expect the menu page to refresh automatically once. However, when implementing the code below, the home page is refreshed first before navigating to the menu page without an auto-refresh. 1)Initia ...

How can you position the input cursor at the end of the default text when navigating through fields with the tab key?

I've implemented tab index in the HTML to navigate from one field to another. In the image below, you can see me tabbing from "Revise" to "Link". https://i.stack.imgur.com/vb6L.png However, when I press tab, the default text in the Link field is fu ...

Is there an alternative to RequestOptionsArgs that I can use in this function?

I am currently working on updating an existing Angular application from version 4.3 to Angular 8. One of the challenges I'm facing is replacing old component classes like ConnectionBackend, RequestOptions, and RequestOptionsArgs with their updated equ ...

A powerful trio: Axios, Typescript, and Promises

I am facing a TypeScript dilemma. I have a REST method that is being called within my http library by Vue action. I want the resolve() method to return the typed array, but if I do not convert it within the action.ts "then" method, I get a '.length do ...

The content within the mat-card-content paragraph exceeds the boundaries of the mat-card container,

I recently began working with Angular Material and came across an issue. When I have a shorter text paragraph, it overflows the card. However, when I use a larger paragraph, the text wraps nicely. Here is the code snippet: <mat-card *ngFor="let s ...

Use contextual type when determining the return type of a function, rather than relying solely on

When using Typescript 2.2.2 (with the strictNullChecks option set to true), I encountered an unexpected behavior. Is this a bug or intentional? interface Fn { (value: any): number; } var example1: Fn = function(value) { if (value === -1) { ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

How to retrieve values from multiple mat-sliders that are dynamically generated using ngFor loop

Creating multiple mat-sliders dynamically in Angular looks like this: <ng-container *ngFor="let parameter of parameterValues; let i = index;"> <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" i ...

Tips for presenting SVG symbols using Interpolation within Angular 7 from a JSON document

When it comes to displaying content in Angular 7 components, JSON is used. However, I have encountered a problem while trying to incorporate SVG icons from our UX team into the component using JSON. Using the img tag restricts me from applying a CSS class ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections. The challenge I'm facing is that both the getter and setter must have the same argum ...

Tips for positioning the labels in a sankey diagram for optimal alignment

When multiple values are the same in this scenario, such as 0, the labels start to overlap. Can anyone provide guidance on how to align these labels vertically? Ideally, I would like them to be positioned at the top of the node/bar. Highcharts.chart(&apos ...

Trouble arises when attempting to transfer cookies between server in Fastify and application in Svelte Kit

In the process of developing a web application, I am utilizing Fastify for the backend server and Svelte Kit for the frontend. My current challenge lies in sending cookies from the server to the client effectively. Despite configuring Fastify with the @fas ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

Importing libraries in TypeScript and JavaScript are not done in the same manner

As I create my own library, I aim for it to be compatible with both javascript and typescript. tsconfig.json { "compilerOptions": { "target": "es2017", "module": "commonjs", &qu ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...

An issue has been identified with the functionality of the router-out

Issue with Router Loading Component Outside of the router-outlet in app.component.ts @Component({ selector : "body", template : `<router-outlet></router-outlet>`, directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: "/aut ...

Display JSON element in Angular only once

Below is the code snippet: <ion-content padding> <h1>Datum: </h1> <ion-list> <ion-item *ngFor="let u of tecaj"> <h2>{{u.datum}}</h2> <h2>{{u.drzava}} | {{u.valuta}}</h2> ...