I am generating random color with a button in Angular app. But with this always adding the value to color variable, so first time it generates a random color but after that always adding six letters to color and it means it is not generating color anymore. So I have to reset color value, but where should I reset the color value?
letters = '0123456789ABCDEF';
color = '#';
getRandomColor(randomColor) {
for (var i = 0; i < 6; i++) {
this.color += this.letters[Math.floor(Math.random() * 16)];
}
}
<button (click)="getRandomColor()">Generate random color</button>
<p [ngStyle]="{color: color}">Random color</p>
{{color}}
I am generating random color with a button in Angular app. But with this always adding the value to color variable, so first time it generates a random color but after that always adding six letters to color and it means it is not generating color anymore. So I have to reset color value, but where should I reset the color value?
letters = '0123456789ABCDEF';
color = '#';
getRandomColor(randomColor) {
for (var i = 0; i < 6; i++) {
this.color += this.letters[Math.floor(Math.random() * 16)];
}
}
<button (click)="getRandomColor()">Generate random color</button>
<p [ngStyle]="{color: color}">Random color</p>
{{color}}
Share
Improve this question
asked Aug 23, 2018 at 11:27
AlperzknAlperzkn
4792 gold badges10 silver badges26 bronze badges
4 Answers
Reset to default 3You need to reset this.color
to #
before adding more hex values to it.
getRandomColor(randomColor) {
this.color = '#'; // <-----------
for (var i = 0; i < 6; i++) {
this.color += this.letters[Math.floor(Math.random() * 16)];
}
}
letters = '0123456789ABCDEF';
color = '#';
getRandomColor(randomColor) {
this.color = "#";
for (var i = 0; i < 6; i++) {
this.color += this.letters[Math.floor(Math.random() * 16)];
}
}
this.color = "#";
before for loop reset the value of color by color = '#'
Right above the loop,
getRandomColor(randomColor) {
this.color = '#';
for (var i = 0; i < 6; i++) {
this.color += this.letters[Math.floor(Math.random() * 16)];
}
}