Angular - How to apply [ngStyle] conditions

AngularNg Style

Angular Problem Overview


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'}">

Angular Solutions


Solution 1 - Angular

For a single style attribute, you can use the following syntax:

<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">

I assumed that the background color should not be set if neither style1 nor style2 is true.


Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">

Solution 2 - Angular

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"

Solution 3 - Angular

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

Solution 4 - Angular

<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>

Solution 5 - Angular

[ngStyle]="{ 'top': yourVar === true ? widthColumHalf + 'px': '302px' }"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMegaTronView Question on Stackoverflow
Solution 1 - AngularConnorsFanView Answer on Stackoverflow
Solution 2 - AngularGili YanivView Answer on Stackoverflow
Solution 3 - AngularApurv ChaudharyView Answer on Stackoverflow
Solution 4 - Angularfahimeh ahmadiView Answer on Stackoverflow
Solution 5 - AngularAjay KumarView Answer on Stackoverflow