typescript 如何生成随机数以在角度 2 上输入表单组索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41755318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:10:51  来源:igfitidea点击:

How to generate random number to input form group index on angular 2

javascriptangulartypescript

提问by John Lesner

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 绑定到模板,如下所示:

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

and the ts file

和 ts 文件

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:

所有这些都很好用。用户可以添加新的输入字段,但我有一个按钮可以生成一个随机数并将随机数设置为输入值。由于我是 Angular 2 的新手,当有多个输入字段时,我似乎无法实现它。生成随机数进入字段的方法如下:

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?

我的getRandomNumber()方法缺少什么来为每个添加的字段生成一个随机数?

回答by John Lesner

I 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)


  }

回答by Rupak Thapa Magar

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

带有 angular 8 的 Github 源