TheScripterX
TheScripterX

Reputation: 268

Problem changing Background-Color with ngStyle

I'm using Angular 7, and my problem is that when I put the directive ngStyle in an "ul" Tag, the style "Color" works ! but with "Background-color" it's not working !

Here's the Template Code:

 <ul class="list-group">
  <li class="list-group-item" [ngStyle]="{color: getColor()}">
    <h4> {{articles}} </h4>
    <button class="btn btn-success" (click)="clickP()">I love It ! {{count}}</button>
    <button class="btn btn-danger" (click)="clickN()">I Hate It ! {{count}} </button>
  </li>
</ul>

And here's the Typescript Code:

  getColor() {
    if (this.count > 0) {
      return "green";
    } else if (this.count < 0) {
      return "red";
    }
  }

I get this error when I'm using "background-color" instead of "color" :

Uncaught Error: Template parse errors: Parser Error: Missing expected : at column 12 in [{background-color: getColor()}] in ng:///AppModule/ArticlesComponent.html@1:30 (" ][ngStyle]="{background-color: getColor()}">

Did I do something wrong ? Thank You.

Upvotes: 4

Views: 3381

Answers (2)

Keith James
Keith James

Reputation: 167

You are almost there you can make this work by adding single quotes like this

<li class="list-group-item" [ngStyle]="{color: getColor(), 'background-color': getBgColor()}">

Alternatively, you can remove the dash and use it with variable camelCase like this

<li class="list-group-item" [ngStyle]="{color: getColor(), 'backgroundColor': getBgColor()}">

You still need the single quotes though.

Upvotes: -1

Sourav Dutta
Sourav Dutta

Reputation: 1332

This should work

 <ul class="list-group">
  <li class="list-group-item" [ngStyle]="{'background-color': getColor()}">
    <h4> {{articles}} </h4>
    <button class="btn btn-success" (click)="clickP()">I love It ! {{count}}</button>
    <button class="btn btn-danger" (click)="clickN()">I Hate It ! {{count}} </button>
  </li>
</ul>

Upvotes: 2

Related Questions