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

Struggling with the error message "Type 'ChangeEvent<unknown>' is not assignable to type 'ChangeEvent<MouseEvent>'" while working with React and TypeScript? Here's how you can tackle this issue

Within the App.tsx file, I encountered an issue with the Material UI Pagination component where it was throwing an error related to type mismatch. The error message stated: Argument of type 'ChangeEvent' is not assignable to parameter of type &ap ...

Mastering the art of navigating through intricate nested properties within JSON data structures

Presented below is a dynamic JSON structure: data = { "name": "deltha", "type": "object", "important": [ "name", "id", "number" ], "information": { "place": { "editable": false, "visible": true }, "info": { ...

How can I format the input type number with a thousand separator as 123.456.789?

When entering the number 123456, I want to see 123.456 displayed in the input field. I tried using my code, but it displays 123,456 instead. Is there a way to ensure that the thousand separator is a dot and not a comma? You can view my code at this link ...

Converting an integer into a String Enum in TypeScript can result in an undefined value being returned

Issue with Mapping Integer to Enum in TypeScript export enum MyEnum { Unknown = 'Unknown', SomeValue = 'SomeValue', SomeOtherValue = 'SomeOtherValue', } Recently, I encountered a problem with mapping integer val ...

Encountering an issue with executing Google API Geocode in JavaScript

I'm having trouble printing an address on the console log. Every time I run the code, I encounter an error message that reads: { "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or &ap ...

Show the Canvas element at the back of the DIV

This particular question requires a clear explanation. My goal is to have the canvas act as a background element on the page, while the main content of the page starts in its usual position. I attempted using separate DIVs with their own Z-index values, bu ...

Activating autocomplete outcomes via AJAX using Cucumber/Capybara/Selenium

Whenever I try to run my tests, the autocomplete dropdown menu doesn't appear unless I physically click on the search input field. This is a Cucumber test that utilizes Selenium Webdriver, and the data is sourced from the Crafty Clicks Address Autoco ...

What is the best way to integrate ngx-translate's pipe for global translation?

I'm currently utilizing the ngx-translate package in order to internationalize my Angular application. When translating text using the translate pipe like so: {{ 'title' | translate }} An issue arises when attempting to use this pipe in ot ...

The attempt to retrieve data from the PHP file using Ajax was unsuccessful

I'm attempting to showcase the content of a PHP file on my HTML page using AJAX. Within my HTML file, I have included the following AJAX code: AJAX Code in get_ajax.html <form action=""> First name: <input type="text" id="txt1" onblur="sh ...

Issue with showing Angular directive

I've been working on implementing an angular dropdown list with Bootstrap. The functionality includes a directive that allows the user to select a menu option from the dropdown and receive an alert message. To see the implementation in action, I have ...

Unlock the secrets of creating a pop-up with qtip

I am working on qtip code that generates a popup when a specific link is clicked. I'm wondering if there's a way to use jQuery to determine if the link with the id "test2" has been clicked or not. Thank you, James <ul> <li><a id= ...

Issues are being faced with the execution of JavaScript on Heroku when using Rails 3.1

After upgrading a Rails 3.0 app to 3.1 on Heroku running on the cedar stack, everything seemed fine except for one major issue - the app's JavaScript wouldn't run. Despite the application.js file being compiled and accessible at myapp.com/assets/ ...

Angular2 Cascading Animations

I have been working on implementing cascaded animations for a list of elements. Although I successfully applied the state triggers, following the guidelines in the documentation, I am encountering an issue where all element states are being applied simult ...

Tips for accessing JSON data stored as keys within a JavaScript object

I'm facing an issue with my Node.js lambda function that involves parsing JSON data received from an external application. The JSON data seems to be malformed and arrives as an object key, shown below: console.log(req.body) This results in: { &apo ...

Integrating Facebook login with Cordova using the cordovaOauth plugin

Encountering issues while setting up FB login for my cordova mobile app. A tutorial followed: http://www.codeproject.com/Tips/1031475/How-to-Integrate-Facebook-Login-into-a-Cordova-App#_comments <script src="js/angular.js"></script> <scrip ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

There seems to be a problem with the full calendar updateEvent feature as it is unable to read the property 'clone'

Struggling to update an event using FullCalendar and a modal. Encounter the 'cannot read property 'clone' of undefined' error when attempting to update. Following the documentation, I utilize the clientEvents method. It is crucial t ...

Using Event Delegation in Practice

I am facing an issue with loading 2 <span> elements from separate ajax scripts onto a webpage upon selection from a dropdown box. Here is a snippet of my code: <span id='room_rate'>1,000</span> // content loaded by one ajax scri ...

Ways to switch classes within a loop of elements in vue.js

I'm just starting to learn vue.js and I'm working on a list of items: <div class="jokes" v-for="joke in jokes"> <strong>{{joke.body}}</strong> <small>{{joke.upvotes}}</small> <button v-on:click="upvot ...

What could be causing JavaScript Ajax calls to fail over SSL specifically on IOS devices, with the exception of IOS

I am encountering an issue with a mobile application I have developed. It makes an ajax xmlHttpRequest request over SSL to another application on the same domain in order to authenticate a user. Strangely, this call fails with response code zero on IOS dev ...