How to set background color of a div in angular?

Viewed 962

I have an angular web app where my html is as follows:

<p class="news-source" style="background-color: {{news.backgroundColor}}">{{news.source.title}}</p>

My component has the following :

this.news = new News()
this.news.backgroundColor = '#E6E6CA'

However, I see that the color does not get set if I use {{news.backgroundColor}}. What is the correct way to set the background color?

style="background-color: #E6E6CA"

This works if I use the hex directly. But, I want to use news.backgroundColor to set the color. So, wondering what is the correct usage.

2 Answers

You need to surround style with [] otherwise, it's just going to be interpreted as a string. Do it like this:

<p class="news-source" [style.backgroundColor]="news.backgroundColor">{{news.source.title}}</p>

You could also define an object in your component, instead of setting each property individually:

public myStyle = {
  "background-color": this.news.backgroundColor
}
<p class="news-source" [style]="myStyle">{{news.source.title}}</p>

as long as news.backgroundcolor is a public member, your approach works fine. ts:

export class myClass {
news = {"backgroundcolor":"#e6e6ca"}
}

html:

<p style="background-color:{{news.backgroundcolor}};"> 

See the example:

If the property / member is private or the scope otherwise inaccessible (null) it obviously won't work.

Also, You should generally be using classes IMO.

Related