Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}"> 
like image 811
MegaTron Avatar asked Mar 14 '18 14:03

MegaTron


People also ask

Can we use ngClass and NgStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

How do you add a background color on NgStyle?

The NgStyle directive lets you set a given DOM elements style properties. This sets the background color of the div to green. The above code uses the ternary operator to set the background color to green if the persons country is the UK else red.


2 Answers

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) }"> 
like image 128
ConnorsFan Avatar answered Sep 20 '22 18:09

ConnorsFan


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" 
like image 26
Gili Yaniv Avatar answered Sep 19 '22 18:09

Gili Yaniv