How to Generate Random String in Angular?

By Hardik Savani May 2, 2024 Category : Angular

Hello,

If you need to see example of angular generate random string. you can understand a concept of angular generate random alphanumeric string. This article goes in detailed on how to generate random string in angular. you can understand a concept of generate random string in angular.

In this example, i will create simple function randomString() with one argument, you can pass length and return random string here.

you can also use this example with angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 version. so let's see bellow example:

Example:

import { Component, VERSION, OnInit } from '@angular/core';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent implements OnInit {

name = 'Angular ' + VERSION.major;

ngOnInit() {

console.log(this.randomString(10))

}

randomString(length) {

var randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

var result = '';

for ( var i = 0; i < length; i++ ) {

result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));

}

return result;

}

}

Output:

9zlENYIVFD

i hope it can help you...

Tags :
Shares