[angular] Angular - How to apply [ngStyle] conditions

I have a div that I want to style based on a condition.

If styleOne is true I want a background colour of red. If StyleTwo is true, I want the background colour to be blue. I've got half of it working with the below code.

    <div id="myDiv" [ngStyle]="styleOne && {'background-color': 'red'}">

Is it possible to add a condition to say:

  • if styleOne is true, do this
  • if styleTwo is true, do this?

Edit

I think i've resolved it. It works. Not sure if it's the best way:

<div id="div" [ngStyle]="styleOne && {'background-color': 'red'} || styleTwo && {'background-color': 'blue'}">

This question is related to angular ng-style

The answer is


[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

You can use an inline if inside your ngStyle:

[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"

A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

[style.background-color]="myColorVaraible"