-2

I am learning angular to set style using angular way so I have create below code. I am trying to set background using below code - but its not working as expected. How to set background using below syntax with [style]? I am creating demo with angular 8.

<code>
   <div [style.background-color]='red'> 
      a
   </div>
</code>
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
bharat
  • 79
  • 1
  • 11
  • [style.background-color]=“'red'” (note the extra quotes) – MikeOne Apr 08 '20 at 17:40
  • Bharat! Did any answer work for you? If yes do consider accepting/upvoting them. [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Nicholas K Apr 09 '20 at 05:41
  • 1
    @NicholasK bharat appears to have a history of posting low quality questions and never accepts answers. It's very frustrating, time-wasting, and clearly not a successful way of learning a new language – Kurt Hamilton Apr 09 '20 at 06:31

2 Answers2

2

<div [style.background-color]='red'>

means that Angular is looking for a variable named red, which it doesn't find hence the style doesn't get applied.

Use:

<div [style.background-color]="'red'">

which informs Angular to use the string value which is evaluates to red.


You can also use the following syntax to avoid any confusion:

<div [ngStyle]="{ background: 'red'}">
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
1

For a background color inline style you would need: [style.background-color]="'red'"

nick
  • 1,880
  • 17
  • 27