Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below:

*ngFor="let data of getTasks(myFormdata); let i=index"

In addition, here is the corresponding code from the ts file:

getTasks(myFormdata) {
    return myFormdata.get('inputs').controls
} 

The functionality works smoothly in allowing users to add new input fields. However, I have encountered an issue with a button that is supposed to assign a random number to each input field. As I am relatively new to Angular 2, I am struggling to implement this feature when there are multiple input fields present. The method responsible for generating and assigning the random number is outlined below:

getRandomNumber() {
    const random = Math.floor(Math.random() * (999999 - 100000)) + 100000;
    const control = <FormArray>this.myFormdata.controls['inputs'];
    control.setValue([{numbers: random, pari: 25}])
}

I would appreciate some guidance on how to modify the getRandomNumber() method so that it generates a unique random number for each additional field that is added.

Answer №1

Here is the solution I came up with:

  generateRandomNumber(i: number) {
    let randomNum = Math.floor(Math.random() * (999999 - 100000)) + 100000;
    const formArray = <FormArray>this.myFormdata.controls['inputs'];
    const newControl = this._fb.group({numbers: +quickpicked, pari: 25});
    formArray.setControl(i, newControl);
  }

Answer №2

export class AppComponent {
  title = 'codegenerator';
  date = new Date();
  codeGenerated = '';
  evtMsg: any;
  randomString() {
 const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
 const stringLength = 10;
 let randomstring = '';
 for (let i = 0; i < stringLength; i++) {
 const rnum = Math.floor(Math.random() * chars.length);
 randomstring += chars.substring(rnum, rnum + 1);
}
 this.codeGenerated = randomstring;
 return 0;
}
}
  <div class="card text-center" style="width: 40rem;">
      <div class="card-head">
        <button (click)="randomString()" class="d-inline bg-primary btn-lg text-white">Generate code</button>
      </div>
      <div class="card-body">
        <h1 class="display-2 text-dark">{{codeGenerated}}</h1>
      </div>
      </div>

Link to GitHub repository with Angular 8 source code

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

Utilizing form data to upload images and send them back to the front end within a React js application

I am working on a project using NestJS and React JS to create an image uploader. In React, I have the following setup: const props = { onChange({ file, fileList }: any) { const fd = new FormData(); fd.append('img& ...

Convert all key types into arrays of that key type using a TypeScript utility type

My interface (type) is currently defined as: interface User { name: string, id: string, age: number, town: string } I have a function now that will search for Users based on specific fields. I prefer not to manually declare an additi ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

Update to using res.get() instead of res.getHeader()

Looking for assistance with the code snippet below: const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|fo ...

I require the ability to access a reference parameter with a dynamically changing name within a Vue template

<div v-for="x in 4" :class="(images[x] === null) ? 'not-removable' : 'removable'" class="img-container"> <input style="display: none" type="file" ...

StopDefault and JSON Placement

We have a form that sends data to an external domain using JSONP to avoid cross-domain limitations. Everything is functioning properly except for preventing the default form submission that triggers a page reload. Below is the HTML code for the form: < ...

Having trouble initializing an array of objects to store data in MongoDB using AngularJS

I am facing an issue while trying to save dynamically created HTML in MongoDB using Mongoose from AngularJS. The problem lies in creating the required object that matches the Mongoose schema I have defined. model code var SegmentSchema = new Schema({ n ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Diagnosing issues with the socket.io event system in a Node.js backend and Angular frontend

To establish a basic event system within my Node backend for notifying clients (Angular application) of specific events (such as when a user changes their profile photo), I am utilizing the socket.io library in the backend and its corresponding 'ngx-s ...

How can I retrieve the handle for an item within a jQuery collection from within the success function of an .ajax() call?

I'm currently facing an issue with a jQuery ajax call that I have firing for each element in a collection identified by a specific jQuery selector. Here's a snippet of the code: $('.myClass').each(function () { $.ajax({ url ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

typescript: exploring the world of functions, overloads, and generics

One interesting feature of Typescript is function overloading, and it's possible to create a constant function with multiple overloads like this: interface FetchOverload { (action: string, method: 'post' | 'get'): object; (acti ...

How to Use Hyperledger Composer's Rest-Server-Api Local-Passport Strategy in an Angular Application without Node.js

Is it possible for me to implement the passport-local strategy in my project, considering that I am using an angular front-end generated by the composer-rest-server tool? I noticed in the documentation for passportjs regarding passport-local, it mentions ...

Is there a specific method that can be implemented in Node.js to compare two strings and identify the common words or letters?

Looking for a solution: var str1="CodingIsFun"; var str2="ProgrammingRocks"; Is there any function that can provide a true value or flag in this case? ...

Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript. var webdriver = require('selenium-webdriver') ...

Angular: monitoring changes in HTML content within a Component or Directive

I have a situation where I am retrieving HTML content from a REST endpoint using a directive and inserting it into a div element using [innerHTML]. Once this HTML content is rendered, I would like to manipulate it by calling a global function. My approach ...

Can you explain the distinction between using get() and valueChanges() in an Angular Firestore query?

Can someone help clarify the distinction between get() and valueChanges() when executing a query in Angular Firestore? Are there specific advantages or disadvantages to consider, such as differences in reads or costs? ...