[英]Changing css class properties based on condition (*ngIf in angular 2)
我希望我的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>
但這是行不通的。 默認情況下,瀏覽器似乎會忽略,並且使用*ngIf
divs
並且只有最后一個樣式會覆蓋其他樣式。 以下是瀏覽器的解釋:
更新:之所以出現這種情況,是因為我正在使用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>
您不能像這樣動態更改文檔的樣式表。 相反,為可能的情況定義類並更改切換器的類。
嘗試這樣的事情:
.ui-select-toggle { /* whatever */ }
.ui-select-toggle.suspended { background: red; }
.ui-select-toggle.active { background: green; }
然后更改切換的類:
<div
class="ui-select-toggle"
[class.suspended]="dropDownBg==='Suspended'"
[class.active]="dropDownBg==='Active'"
>
</div>
一個元素可以具有多個CSS類,因此您可以在主類中定義通用屬性(ui-select-toggle),並為輔助類中的每個狀態定義特定的額外屬性。
在您的情況下,您必須創建3種樣式,並使用指令
[NgClass] = "{style1: condition, style2: condition, style3: condition}
如果它只是一個屬性(這里是背景),則可以執行以下操作:
<div [style.background]="...">...</div>
在您的情況下,可能是:
<div [style.background]="dropDownBg === 'Active' ? 'green' : dropDownBg === 'Suspended' ? : red : dropDownBg === 'Disabled' ? 'grey' : 'black'">...</div>
黑色是您的后備顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.