javascript - randomString 未在 HTMLInputElement.onclick Typescript 中定义

标签 javascript angular typescript

我想创建一个函数来生成随机字符串或数字。

我在 ts 中的函数是这样的:

  randomString() {
    let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    let string_length = 8;
    let randomstring = '';
    for (let i = 0; i < string_length; i++) {
      let rnum = Math.floor(Math.random() * chars.length);
      randomstring += chars.substring(rnum, rnum + 1);
    }
  }

HTML代码

    <form [formGroup]="addProductForm">
          <div class="input-field col s12">
                <input formControlName="Line_num" type="button" value="Create Random String" onClick="randomString();">  
  <input type="text" name="Line_num" value="">    
            </div>
    <form>

当我单击按钮时,显示此错误: Uncaught ReferenceError :TMLInputElement.onclick 中未定义 randomString

现在, 我改变这个,

this.addProductForm = this.fb.group({
    'Line_num': new FormControl(this.randomString(), Validators.required),
    });

在函数中

   randomString() { 
  return Math
    .random() // Create a random number
    .toString(36) // Convert it to string (26 letters + 10 numbers)
    .split('') // Creates an array of those letters
    .slice(-8) // Take the last height ones
    .join(''); // Join them back to create a string
}

HTML代码

 <form [formGroup]="addProductForm">
    <div class="input-field col s12">
        <input type="text" formControlName="Line_num" name="Line_num">
</div>
</form>

问题已解决

最佳答案

创建随机字符串的更简单方法怎么样?

randomString() { 
  return Math
    .random() // Create a random number
    .toString(36) // Convert it to string (26 letters + 10 numbers)
    .split('') // Creates an array of those letters
    .slice(-8) // Take the last height ones
    .join(''); // Join them back to create a string
}

这更容易阅读并且可以解决您的问题。

供您编辑:

this.addProductForm = this.fb.group({
  'Line_num': new FormControl(this.randomString(), Validators.required)
});

在 HTML 中

<form [formGroup]="addProductForm">
  <input type="text" formControlName="Line_num" name="Line_num">
</form>

关于javascript - randomString 未在 HTMLInputElement.onclick Typescript 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49252244/

相关文章:

javascript - 在服务器端无法访问客户端上更改标签文本

javascript - 在 Javascript 中推送到 for 内的数组

angular - 使用 glob 定位任何具有特定前缀的嵌套文件夹

javascript - Angular 2. 错误 : Loading chunk failed

javascript - 在 DOM 元素发起的请求上设置请求 header

javascript - Crafty.js 无法识别与其他实体的碰撞

JSON对象列表的Angular 6 ngbTypeahead过滤器

用于将数字格式化并打印为正数的 Angular HTML 代码(不带减号)

javascript - 在 Angular6 中对一个组件使用多路由

javascript - 我想在单击关闭按钮 Angular 6 后隐藏 div