![](/img/trans.png)
[英]Angular 6 [ngClass] not working with boolean in component.js
[英]Is it possible to use [ngClass] on an app component where the class is inside the component for Angular 6?
我有一個angular 6應用程序,我正在嘗試將另一個CSS類應用於app.component.html
文件中的一個我的應用程序組件。 基本上,我想根據條件更改應用程序頁腳的顏色,而其他所有情況都不顯示頁腳。 因此,我的代碼如下所示:
app.component.html
<router-outlet></router-outlet>
<my-footer [ngClass]="{ 'my-class' : true }"></my-footer>
我-footer.css
:host {
background-color: black;
color: white;
}
.my-class {
background-color: red;
}
是否可以以這種方式使用[ngClass]
,而該類存在於我對其施加條件的組件中? 我發現如果將.my-class
放在app.component.css
文件中,那么它將按預期工作。 但是,我想將樣式保留在它們所屬的組件中。
謝謝!
將組件樣式保留在組件內。 您想將方法更改為:
<my-footer *ngIf="ifMyCondition === true"></my-footer>
在這種情況下,僅當您的條件為true時,它才會構造頁腳。
UPDATE--
正如您在評論中提到的那樣,我仍然建議您處理組件內部的組件需求,而不要依賴外包(在您的情況下是父級?)來更改組件屬性。 因此,我建議您在孩子中使用Input()來從父母那里獲得狀況的狀態,然后根據需要進行處理。
家長:
someCondition: boolean;
HTML:
<my-footer [condition]="someCondition"></my-footer>
兒童:
@Input() condition: boolean;
現在,每次父母中的條件發生變化時,與孩子的綁定都會不斷更新他,因此您可以根據父母中的綁定條件來管理子組件中的所需內容。
使用選擇器:host.my-class
似乎可以正常工作,如本stackblitz所示。
我-footer.css
:host {
background-color: black;
color: white;
}
:host.my-class {
background-color: red;
}
app.component.html
<my-footer [ngClass]="{ 'my-class' : condition }"></my-footer>
您可以根據條件申請課程。
您可以執行以下操作:
app.component.html
<router-outlet></router-outlet>
<my-footer [ngClass]="{ 'my-class' : displayFooterBg() }"></my-footer>
app.component.ts
displayFooterBg = () => {
if (this.condition === true) {
return true;
} else {
return false;
}
}
您可以將類作為子組件的輸入。
父母(HTML):
<my-footer [classValue]="class1"></my-footer>
兒童(TS):
@Input() public classValue = 'default-class';
兒童(HTML)
<div ngClass = {{classValue }}></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.