最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Generating random color with button in Angular app - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 3

You 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)];
          }
        }
发布评论

评论列表(0)

  1. 暂无评论