我想创建一个函数来生成随机字符串或数字。
我在 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/