What is preventing my function from retrieving user input from an ngForm?

I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input.

The "data" parameter in my submit function is the 'value' attribute of the ngForm. For instance, if the user inputs "hello world," logging data to the console will display this

{word_1: "hello", word_2: "world" }
and typeof keyword indicates it's an object.

The function crashes my app at the first for loop, and I'm struggling to identify the cause. Can anyone assist?

Key points to consider:

  • I'm following this method because the number of inputs is unknown beforehand, so I won't know how many keys there will be (word_1 . . . word_N).
  • The variable this.inputBoxes doesn't have a value until after onClickSubmit function is called, hence why I'm trying to figure out how to "declare a global array but instantiate it later" in typescript.

This is the function I'm using to extract "hello" and "world," but it keeps crashing my webpage without clear explanation.

component.ts

  public inputBoxes: any; 
  private keys: Array<string>;

onClickSubmit(data) {

    let num = parseInt(this.inputBoxes); 
    this.keys = new Array(num);

    for (let idx = 0; idx < num; idx++){
      this.keys[idx] = Object.keys(data)[idx];
    }


    for (let i = 0; i < num; i++){
      console.log(data.keys[i]);
    }

 }

This is my html, although I doubt anything here is causing the issue

component.html

<p>How many words will you be using?</p>
<select (change)="updateInputBoxes($event)">
    <option value="">Select Count</option>
    <option *ngFor="let num of dropdown_numbers" value={{num}}> {{num}} </option>
</select>

<div *ngIf="inputBoxes">
    <form #allWords = "ngForm" (ngSubmit)= "onClickSubmit(allWords.value)" >
        <label>Enter the Words for your Crossword</label>
        <div *ngFor="let box of createInputBoxes">
            <input required ngModel name="word_{{box}}" #word="ngModel" class="form-control">
            <div class="alert alert-danger" *ngIf=" word.touched && !word.valid"> Missing word, please insert a word </div> 
        </div>
        <button type="submit" value="submit">Submit</button>
    </form>
</div>

Answer №1

you can utilize [(ngModel)] in a more convenient manner

inputs:any[]=[]
inputBoxes: any; 

The .html with [(ngModel)]

    <!--check out the select with ngModel-->
    <select [(ngModel)]="inputBoxes" (ngModelChange)="inputs=inputs.slice(0,$event)">
        <option value="">Select Count</option>
        <!--You have the option to use a variable or an array directly-->
        <option *ngFor="let num of [1,2,3,4,5,6,7,8,9,10]"
            [value]="num"> {{num}} </option>
    </select>
    <div *ngIf="inputBoxes">
        <form #allWords = "ngForm" (ngSubmit)= "onClickSubmit(allWords.value)" >
            <label>Enter Words for Your Crossword</label>
            <!--you can apply pipe slice, ensuring it's the same array as the select
                use "let i=index" to obtain the index starting from 0
             -->
            <div *ngFor="let box of [1,2,3,4,5,6,7,8,9,10] |slice:0:inputBoxes;let i=index">
               <!--the ngModel is inputs[i], which automatically populates your array inputs
                   accordingly
               -->
                  
                <input required [(ngModel)]="inputs[i]" name="word_{{box}}" #word="ngModel" class="form-control">
                <div class="alert alert-danger" *ngIf=" word.touched && !word.valid"> Missing word, please provide a word </div> 
            </div>
            <button type="submit" value="submit">Submit</button>
        </form>
    </div>

within the function onClickSubmit, you are able to

onClickSubmit(value:any)
{
    console.log(value) //<--retrieve the form value
    console.log(this.inputs)  //<--obtain the this.inputs array
}

View 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

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

What is the best way to send multiple values from node.js to typescript?

My Node.js post API currently returns a token, but I want it to include the user's email, id, etc: app.post('/auth', function (req, response) { const body = req.body; console.log(req.body); let query = `select * from users wher ...

Changes made in React are not reflected in the DOM

import React, { Component } from "react"; import ReactDOM from "react-dom"; import "./index.css"; class App extends Component { constructor(props) { super(props); this.state = { text: "", listItem: [] } this.onChangeInpu ...

The Flask web API is unable to process image files sent through AJAX requests

My Flask API is quite basic and it interacts with a DNN model. The Python backend code looks something like this: from flask import request from flask import jsonify from flask import Flask import io app = Flask(__name__) @app.route("/predict" ...

Creating a TypeScript generic type for the "pick" function to define the types of values in the resulting object

I am facing an issue while writing the type for the pick function. Everything works smoothly when picking only one key or multiple keys with values of the same type. However, if I attempt to pick a few keys and their values are of different types, I encoun ...

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 React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

Angular 2's Implementation of Hierarchical Dependency Injection

I'm encountering a problem with my Angular 2 application. I have a root component, AppComponent, where I've injected a service called ProductService. Now, I am trying to resolve this service in one of the child components, ProductList, but I keep ...

Calculate the total duration between two times and, if the difference is more than 10 minutes,

I need to calculate the duration between two dates, start_time and end_time. If the minutes component is greater than 10, I want to round up the hours component. For example: 12 minutes different - rounded up to 1 hour 1 hour 31 minutes difference - roun ...

What advantages does Angular's Dependency Injection offer for a basic object setup?

The Angular documentation provides an example of injecting a value (configuration object) using @inject in the constructor for scenarios where a class is not being injected. https://angular.io/guide/dependency-injection#non-class-dependencies I managed t ...

Revealing the Webhook URL to Users

After creating a connector app for Microsoft Teams using the yo teams command with Yeoman Generator, I encountered an issue. Upon examining the code in src\client\msteamsConnector\MsteamsConnectorConfig.tsx, I noticed that the webhook URL w ...

A script page in Wordpress generates a numerical value in the URL

I created a script named search.php which utilizes various search engines APIs to display search results. From this file, I have developed a Page template and incorporated the simplePagination plugin The issue arises when I click on a page within the pag ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

Tips for managing update logic in the server side with sveltekit

Currently, I am using Sveltekit and I am facing a dilemma regarding updating input data. The actual update process is straightforward, but there is an issue that arises when trying to send an update API request immediately, as it requires an accessToken to ...

Tips for adding a time increment of 24 hours to a date variable in Angular 6

My goal is to update a date variable called EndDate stored in localStorage by adding exactly 24 hours to it. The current value in the localStorage is Sun Jun 09 2019 20:39:44 GMT+0530 (India Standard Time). var endDate = new Date(); endDate.setDat ...

The 'type' property is not present in the 'ChartComponent' type, however, it is necessary in the 'ApexChart' type

Encountered an error highlighted in the title: Property 'type' is missing in type 'ChartComponent' but required in type 'ApexChart'. Any attempt to resolve this issue led to another error message: Type '{ type: string; ...

Tips for accessing a value from a setInterval function

Is it possible to retrieve a value from the setinterval function in JavaScript? $.ajax({ type : "POST", url:"<?php echo TESTMINE_APP_URL; ?>/ajax/export-details", data:'paginationHash='+paginationHash+'&exp ...