I need a function that can generate a random string or number for me.
Initially, my function in TypeScript looked like this:
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 code:
<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>
Upon clicking the button, I encountered this error: Uncaught ReferenceError: randomString is not defined at TMLInputElement.onclick
To fix this issue, I made the following changes:
this.addProductForm = this.fb.group({
'Line_num': new FormControl(this.randomString(), Validators.required),
});
In the modified function:
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
}
Updated HTML code:
<form [formGroup]="addProductForm">
<div class="input-field col s12">
<input type="text" formControlName="Line_num" name="Line_num">
</div>
</form>
By implementing these changes, the problem was successfully resolved.