Changing css class properties based on condition (*ngIf in angular 2)

ABGR picture ABGR · Jun 28, 2017 · Viewed 9.5k times · Source

I want my css class to change based on condition. I'm trying to use this:

<div *ngIf="dropDownBg==='Active'">
<style type="text/css">
.ui-select-toggle{
    background: green !important;
  }
</style>

</div>


<div *ngIf="dropDownBg==='Suspended'">
<style type="text/css">
.ui-select-toggle{
    background: red !important;
  }
</style>

</div>

<div *ngIf="dropDownBg==='Disabled'">
<style type="text/css">
.ui-select-toggle{
    background: grey !important;
  }
</style>

</div>

But this doesn't work. By default browser seems to be ignoring and divs with *ngIf and only the last style overrides the others. Below is the browser interpretation:

enter image description here UPDATE: This scenario arose because I'm using ng-select dropdown which internally uses class 'ui-select-toggle'over which I don't have any control. So WEIRD people downvoting this question, please take a note of that.

This is the code:

<div style="min-width: 200px;position: absolute;right: 0">
           <ng-select 
                   [items]="items"
                    (selected)="selected($event)"
                    [active]="selectedItem"
                     (removed)="removed($event)"
                  placeholder="Select a number">
          </ng-select>
</div>

Answer

Ondra Koupil picture Ondra Koupil · Jun 28, 2017

You can't dynamically change stylesheet of the document like this. Instead, define classes for possible situations and change the toggle's class.

Try something like this:

.ui-select-toggle             { /* whatever */ }
.ui-select-toggle.suspended   { background: red; }
.ui-select-toggle.active      { background: green; }

And then change class of the toggle:

<div 
    class="ui-select-toggle" 
    [class.suspended]="dropDownBg==='Suspended'"
    [class.active]="dropDownBg==='Active'"
>
</div>

An element can have several CSS classes, so that you can define common properties in main class (ui-select-toggle) and extra properties specific for each state in the secondary class.