Tips for collecting user input while iterating through an array

I am working on a list that iterates over an array and includes input tags. I need to figure out how to retrieve the values from the text boxes after clicking a button, as the input boxes are generated based on the length of the list.

<div>
  <div *ngFor="let arrayitems of arrayElements">
    <P>{{arrayitems}}</P>
    <input type ="text" placeholder="{{arrayitems}}">
  </div>
  <button (click)="submitFunction()" style="margin-top:10px">CLICK ME!</button>
</div>

TypeScript:

 arrayElements : any;

  ngOnInit(){
    this.arrayElements=["listElementOne","listElementTwo","listElementThree","listElementFour","listElementFive","listElementSix"];
  }
  submitFunction(){
    alert("Function Called");
    console.log("print all the values taken from the input tag");

  }

Access the Stack Blitz Link here

Answer №1

To properly bind values, it is necessary to store them in a separate array and then utilize ngModel for binding.

Here is the revised app.component.ts file:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  arrayElements : any;

  items: string[] = [];

  ngOnInit(){
    this.arrayElements=["listElementOne","listElementTwo","listElementThree","listElementFour","listElementFive","listElementSix"];
  }
  submitFunction(){
    console.log(this.items);
  }
}

For the updated app.component.html:

<div>
  <div *ngFor="let arrayitems of arrayElements;let i = index;">
    <p>{{arrayitems}}</p>
    <input type ="text" [(ngModel)]="items[i]" placeholder="{{arrayitems}}">
  </div>
  <button (click)="submitFunction()" style="margin-top:10px">CLICK ME!</button>
</div>

An updated version of your code can be found at https://stackblitz.com/edit/input-tag-iterating-over-array-2fezah

Answer №2

Even though this may not be the conventional angular approach, you have the option to utilize ElemenRef for querying all inputs.

constructor(private elRef: ElementRef) { }

submitFunction() {
  const list: NodeList = this.elRef.nativeElement.querySelectorAll("input");

  list.forEach((el: HTMLInputElement, idx) => {
    console.log(`el${idx}: ${el.value}`);
  });
}

Check out a live demo

However, it is recommended to explore ReactiveForms as well.

Answer №3

Could you please provide further details regarding the response you are receiving?

<P>{{arrayitems}}</P>.

I assume it is returning as undefined?

Answer №4

Make sure to assign unique identifiers to each input field on the page.

<input type ="text" id="{{uniqueId}}" placeholder="{{placeholderText}}">

When submitting the form, locate elements by their ids and retrieve their contents from the "value" property.

for (const elementId of this.arrayElements) {
    const element = <HTMLInputElement>document.getElementById(elementId)
    const content = element.value
    console.log(content)
}

It appears to be functioning properly, although I am uncertain about the usage of the "arrayItems" syntax in app.component.html.

Answer №5

In my app.component.html file, I have implemented a new change method for the input field.

<div>
  <div *ngFor="let arrayitems of arrayElements">
    <P>{{arrayitems}}</P>
    <input type ="text" (change)="inputChange($event, arrayitems)" 
           placeholder="{{arrayitems}}">
  </div>
  <button (click)="submitFunction()" style="margin-top:10px">CLICK ME! 
  </button>
</div>

The app.component.ts file contains the definition for the input change method which assigns the input value to the result with the element name as the key. The submitFunction filters the result and returns a list of results.

export class AppComponent implements OnInit  {
  arrayElements : any;
  result = {};

  ngOnInit(){
    this.arrayElements= ["listElementOne","listElementTwo","listElementThree","listElementFour","listElementFive","listElementSix"];
  }
  
  inputChange(e, itemName) {
    this.result[itemName] = e.target.value
  }

   submitFunction(){
    const submitResult = this.arrayElements.map(element => {
      if (this.result[element]) {
        return this.result[element];
      }
    })
    .filter(e => !!e)

    console.log(submitResult)
    alert("Function Called");
  }
}

I hope this explanation helps you understand the code better!

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

Maintaining a JavaScript script within the local project directory and integrating it for use with Angular

I could use some assistance. I am currently working on an Angular project and making API calls (GET/PUT) to a remote server. In order to improve the performance of my application, I decided to store the necessary JS file locally in the assets folder. Init ...

Using Angular 2 to round a calculated number within HTML

In the HTML code, there is a calculated number associated with Component1. Component1 serves as a tab page within a Bootstrap tab panel. Below is the HTML code with the tab panel: <div id="minimal-tabs" style="padding:75px;padding-top:60 ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

Angular 6 - detecting clicks outside of a menu

Currently, I am working on implementing a click event to close my aside menu. I have already created an example using jQuery, but I want to achieve the same result without using jQuery and without direct access to the 'menu' variable. Can someon ...

`Lively Flames But Repository Chills When Applying Techniques With Reaction`

This is a unique question that cannot be easily answered with a quick online search. /* Story Behind the Question - OPTIONAL */ I recently started a new project where I aimed to strictly adhere to Redux Patterns while utilizing Google Firestore as my pre ...

Is there a way to establish a boundary for the forEach function in TypeScript?

In my web-based game, I use the forEach command to retrieve the team players in the lobby. However, for a specific feature in my game, I need to extract the id of the first player from the opposing team. How can I modify my current code to achieve this? T ...

Can an HTTP response be considered a single element in an Observable stream from RxJS?

Currently, I am expanding my expertise in RxJs and delving deeper into the world of streams. One aspect that intrigues me is comparing an Http response to an Observable created by using of(). Is it accurate to equate a JSON response to the element 'a ...

Automatically assigning IDs to all elements on an Angular webpage

We are currently developing an enterprise web application and have brought on board an e2e test engineer to automate tests. The test engineer has requested that we assign IDs to all elements in our pages. Is there a tool or method available to automatical ...

Creating a repeating sequence in HTML: A step-by-step guide

I have an HTML file containing a portfolio. Each portfolio item is structured like this: <div class="item"> <div class="portfolio-item"> <a href="img/portfolio-item-1.jpg" data-lightbox="ima ...

Is there a method in Node.js to pause file reading and terminate the entire process within the eachLine function of line-reader?

Here is a code snippet that I've been working on: const lineReader = require('line-reader'); var truevar = false; async function readLines(filename, processLine) { return new Promise((resolve, reject) => { lineReader.eachLin ...

transfer item between a mother and offspring

In my project, I have a convention object that needs to be passed as an input to a child component. The convention ID is displayed correctly in the child's template, however, I encounter an issue where the convention appears as undefined when trying t ...

Updating the value of a variable in a separate file with Node.js

I'm facing a business scenario that can be likened to a challenging situation. To simplify, here's the problem: File1.ts import * from 'something'; export const var1="value of var1"; //assume there is a variable 'x' ...

Issue with text displaying as "-webkit-standard" in font dropdown menu on Safari browser detected in Tinymce

There seems to be a Tinymce bug where the text "-webkit-standard" shows up in Safari's font dropdown. As seen in the attached image, it appears once in Chrome (-webkit-standard) and again in Safari. Has anyone else encountered this issue? https://i.ss ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

What is the best way to activate ngModelChange for a custom input field?

I have developed a custom input component and here is the code: html: <input class='ctrl__counter-input' maxlength='10' type='text' [value]="counterValue" [ngModel]="counterValue" (ngModelChange)="onKey(in ...

Can we refactor by using a distinct function?

I'm working on a table component that handles several columns in a similar way. I'm wondering if there is a more efficient way to optimize this code, perhaps by creating a separate function for it? import useTableStyles from 'admin/compo ...

The instance is referring to a property or method that is not defined, but being used during rendering. Verify that the property is reactive and included in the data option

I'm a newcomer to vue JS and facing a challenge with creating vue class components. My setup includes: @rails/webpacker: "^5.1.1" typescript: "^4.0.2" vue: "^2.6.11" vue-class-component: "^7.2.5" Below is the ...

Issue with ADFS 2016 oAuth: Users not being redirected to login page post logout

Having an issue with ADFS 2016 and my Angular application using ng2-adal js for authentication and authorization. After users logout, they are not redirected back to the login page. Debug traces in Event Viewer show the following error: Error: OAuthSignou ...

Challenges with utilizing Ionic Native in a cross-platform application

I am currently developing an application using Ionic 2 that can function both as a website in a browser and as a mobile app on iOS and Android. One key aspect of the app is its use of the SQLite plugin when accessed on mobile devices. However, I have encou ...