Angular - How to apply [ngStyle] conditions
Asked Answered
R

6

140

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'}">
Royall answered 14/3, 2018 at 14:57 Comment(0)
A
281

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) }">
Asomatous answered 14/3, 2018 at 15:5 Comment(0)
B
61

You can use an inline if inside your ngStyle:

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

A better 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"
Bespectacled answered 14/3, 2018 at 15:5 Comment(0)
J
41
[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"
Jupiter answered 6/3, 2019 at 11:22 Comment(0)
N
5
<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>
Nadeen answered 31/5, 2020 at 12:21 Comment(0)
G
4
[ngStyle]="{ 'top': yourVar === true ? widthColumHalf + 'px': '302px' }"
Gremial answered 27/5, 2021 at 13:44 Comment(0)
M
0

Try this:

[ngStyle]="{'margin-left': step.stepNo == 1 ? '-15px' : '-30px'}"
Messier answered 3/12, 2023 at 5:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.