I have a Dynamic form input where the user can press a button to add more input fields that will be bound to the template with ngFor like this:
*ngFor="let data of getTasks(myFormdata); let i=index"
and the ts file
getTasks(myFormdata) {
return myFormdata.get('inputs').controls
}
All this works great. The user can add new input fields, but I have a button that will generate a random number and set the random number to the input value. Since I am new to Angular 2, I can't seem to make it happen when there is more than one input field. The method to generate the random number into the field is the following:
getRandomNumber() {
const random = Math.floor(Math.random() * (999999 - 100000)) + 100000;
const control = <FormArray>this.myFormdata.controls['inputs'];
control.setValue([{numbers: random, pari: 25}])
}
What is missing from my getRandomNumber()
method to make it generate a random number for each added field?
I have a Dynamic form input where the user can press a button to add more input fields that will be bound to the template with ngFor like this:
*ngFor="let data of getTasks(myFormdata); let i=index"
and the ts file
getTasks(myFormdata) {
return myFormdata.get('inputs').controls
}
All this works great. The user can add new input fields, but I have a button that will generate a random number and set the random number to the input value. Since I am new to Angular 2, I can't seem to make it happen when there is more than one input field. The method to generate the random number into the field is the following:
getRandomNumber() {
const random = Math.floor(Math.random() * (999999 - 100000)) + 100000;
const control = <FormArray>this.myFormdata.controls['inputs'];
control.setValue([{numbers: random, pari: 25}])
}
What is missing from my getRandomNumber()
method to make it generate a random number for each added field?
2 Answers
Reset to default 6I got the solution... the following is my solution
getRandomNumber(i: number) {
let random = Math.floor(Math.random() * (999999 - 100000)) + 100000;
const control = <FormArray>this.myFormdata.controls['inputs'];
const random = this._fb.group({numbers: +quickpicked, pari: 25});
control.setControl(i, random)
}
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>
Github source with angular 8