根据条件更改 css 类属性(角度 2 中的 *ngIf)

Rah*_*edi 2 css angular-ngselect angular

我希望我的 css 类根据条件进行更改。我正在尝试使用这个:

<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>
Run Code Online (Sandbox Code Playgroud)

但这不起作用。默认情况下,浏览器似乎忽略divs*ngIf并且只有最后一个样式覆盖了其他样式。以下是浏览器解释:

在此处输入图片说明 更新:出现这种情况是因为我正在使用ng-select下拉菜单,它在内部使用了我无法控制的类“ui-select-toggle”。所以奇怪的人反对这个问题,请注意这一点。

这是代码:

<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>
Run Code Online (Sandbox Code Playgroud)

Ond*_*pil 6

您不能像这样动态更改文档的样式表。相反,为可能的情况定义类并更改切换的类。

尝试这样的事情:

.ui-select-toggle             { /* whatever */ }
.ui-select-toggle.suspended   { background: red; }
.ui-select-toggle.active      { background: green; }
Run Code Online (Sandbox Code Playgroud)

然后更改切换的类:

<div 
    class="ui-select-toggle" 
    [class.suspended]="dropDownBg==='Suspended'"
    [class.active]="dropDownBg==='Active'"
>
</div>
Run Code Online (Sandbox Code Playgroud)

一个元素可以有多个 CSS 类,因此您可以在主类 (ui-select-toggle) 中定义通用属性,并在次类中定义特定于每个状态的额外属性。