How to generate random colors for list

#1

In list of items generate random colors for background.Each item background different color how to pass 7 selected colors. help me guys

1 Like
#2

It depends on how you are declaring your list, but if you have an array of items you can add the background color as a property to each item:

$scope.items = [
    { 
          id: 1,
          backgroundColor: "#911d24" 
    },
    { 
          id: 2,
          backgroundColor: "#acb531" 
    },
    ...
];

Then in the html you set the style using ng-style:

<div ng-repeat="item in items" class="item" ng-style="{'background-color': item.backgroundColor}">
    Item {{ item.id }}
</div>

See this codepen: http://codepen.io/anon/pen/rajgbg?editors=101

#3

thanks for replying @brandyshea
i am looking for data getting from server or pull to refresh add new item and how pass color.not to pass colors to json. fixed 10 colors placing on JavaScript randomly selected to item.how to pass color to item.

#4

Thankfully, Paul Irish has a really good example for this.
http://www.paulirish.com/2009/random-hex-color-code-snippets/

#5

That’s pretty sweet. Haven’t seen that code snippet before. :smile:

Not sure if that is completely practical since you could generate a background color like #111111 while using a text color of #000000. xP

#6

Thats the danger of using a random value.
You could add some kind of logic to say if the value ends of being #111111, run math.random

#7

Hello @andrewmcgivery,

If you need that’s the color I used ( taken from gmail label colors with the text to use for each color )

To me it’s the best way to have a wide choice of color while being sure of readability.

Id,color,text-color
18,#d7cdcd,#5a4f4f,
17,#ffea94,#9b7962,
16,#d1bde2,#593f3c,
15,#a8b4d0,#445171,
14,#9ec6e2,#205668,
13,#c1d897,#587a52,
12,#f3c098,#b75b26,
11,#e6adae,#c25248,
10,#f2bfd9,#b75e90,
9,#666666,#eeeeee,
8,#775352,#ded4d4,
7,#d7d1e9,#5c4aab,
6,#d0d4e9,#3e56a6,
5,#c1dde4,#007790,
4,#d0dad1,#3e6b46,
3,#d05d17,#f4d6c4,
2,#b0322b,#eccbca,
1,#9f3879,#e8cdde,

#8

thanks a lot @mhartington

#9

Html File:

<a mat-list-item *ngFor=“let Dist of DistributorList; let i = index”>

{{Dist.DistributorTitle | uppercase | slice:0:2}}

TS File:

getRandomColor() {
var color = Math.floor(0x1000000 * Math.random()).toString(16);
return ‘#’ + (‘000000’ + color).slice(-6);
}
Screen Shot:

#10

Hi, when i am trying the solution, getting this error
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ‘background-color: #c597fa’. Current value: ‘background-color: #d124d1’.