[英]How to conditionally apply styles on the component tag based on the visibility of component contents?
假設我有一個像這樣的組件,其中包含顯示或隱藏組件內內容的邏輯:
@Component({
selector: 'hello',
template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`,
styles: [`h1 { font-family: Lato; } div { border: 1px solid blue }`]
})
export class HelloComponent {
@Input() name: string;
visible: boolean;
ngOnInit() {
this.visible = this.name === "Stranger"
}
}
我在另一個組件中這樣使用它:
<div class="container">
<hello class='hello-class' name="Stranger"></hello>
<!-- This will not be visible -->
<hello class='hello-class' name="Not stranger"></hello>
</div>
我將一些 styles 應用於hello
組件,如下所示:
.hello-class {
display: block;
margin-bottom: 80px;
}
由於組件中的條件,第二次使用hello
組件將是不可見的。 但即使組件不可見,我添加到hello-class
的 styles 也會應用於組件。
我無法將條件移動以向父級顯示/隱藏組件。 所以我不能在組件之前做一個*ngIf
。
只有當組件可見時,我才能應用這種樣式嗎?
這是說明問題的 stackblitz 的鏈接: https://stackblitz.com/edit/angular-ivy-mfrb7j
由於沒有子節點,您可以使用 css 選擇器執行此操作:
.hello-class:not(:empty) {
display: block;
margin-bottom: 80px;
}
通過使用:not(:empty)
它檢查元素(組件的宿主元素)是否有子元素。 如果它沒有子項,則該樣式將不適用。
ngClass 的條件樣式也適用於這種情況。
所以在你的 HTML 你會放:
<div class="container">
<hello [ngClass]="{'hello-class': visible}" name="Stranger"></hello>
<!-- This will not be visible -->
<hello [ngClass]="{'hello-class': visible}" name="Not stranger"></hello>
</div>
所以當 visible = true 時,它將應用 'hello-class' 樣式。
下面的擴展答案
選項1:
自定義屬性綁定 & ngClass
hello.component.ts - 使父組件中的“可見”屬性可綁定:
@Component({
selector: 'hello',
template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`,
styles: [`h1 { font-family: Lato; } div { border: 1px solid blue }`]
})
export class HelloComponent {
@Input() name: string;
@Input() visible: boolean;
ngOnInit() {
this.visible = this.name === "Stranger"
}
}
parent.component.html - 綁定到 hello 組件的“可見”屬性並使用 ngClass 應用條件樣式:
<div class="container">
<hello [visible]="visibility" [ngClass]="{'hello-class': visibility}" name="Stranger"></hello>
<!-- This will not be visible -->
<hello [visible]="visibility" [ngClass]="{'hello-class': visibility}" name="Not stranger"></hello>
</div>
parent.component.ts - 添加本地屬性“可見性”:
visibility: boolean;
選項 2
本地參考 & ngClass
或者,如果您無法向 parent.component.ts 文件添加任何內容,您可以在 html 中完成所有操作。 為此,您也不需要將@Input()
裝飾器添加到您的 hello.component.ts 文件中。 看起來有點粗糙,但它確實有效。
parent.component.html - 使用本地引用來觸發 ngClass 的條件:
<div class="container">
<hello #a [ngClass]="{'hello-class': a.visible}" name="Stranger"></hello>
<hello #b [ngClass]="{'hello-class': b.visible}" name="Not stranger"></hello>
</div>
Append 變量的組件名稱輸入。
public helloNames = [ 'Stranger', 'Not stranger'];
然后在組件中,執行以下操作。
<div class="container">
<hello class='hello-class' *ngIf="helloNames[0] == 'Stranger'" name="helloNames[0]"></hello>
<!-- This will not be visible -->
<hello class='hello-class' *ngIf="helloNames[1] == 'Stranger'" name="helloNames[1]"></hello>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.