josip
josip

Reputation: 167

Angular passing the expression to style

I have a problem on how to pass an expression to angular style and this is what i have:

color = '#';
letters = ['000000','FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF','C0C0C0'];

this.color += this.letters[Math.floor(Math.random() * this.letters.length)];

HTML:

[style.background-color]="'expression'"

I want to get random color from letters and set it as background. console.log(this.color); returns me one of colors from letters but i can't figure how to use expression in html.

Thaks for reading and help!

Upvotes: 0

Views: 278

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58553

You can use it like :

[ngStyle]="{'background-color': color}"
// or
[style.background-color]="color"

Or you can just create a function and use it like , this will generate random colour each time it called

Component Side :

getColor(){
    return `#${this.letters[Math.floor(Math.random() * this.letters.length)]}`;
}

Template Side :

[ngStyle]="{'background-color': getColor()}"
// or
[style.background-color]="getColor()"

WORKING DEMO (Hit refresh to get random colours each time)

Upvotes: 2

Related Questions