[Angular] Angular Component Host Style

Angular 內有提供針對 Component 本體樣式描述的特別語法,分別是 :host:host-context 這兩者使用,可以讓 Component 的樣式更模組化。而這篇文章就針對這兩者的用法做說明

:host

:host 可用來描述本體 component 的樣式呈現方式,例如

1
2
3
4
5
:host{
display: block;
height: 100px;
background: grey;
}

這樣就可以針對 Component 本身做樣式設定

如果想要透過外部做額外的樣式複寫,這時候可以搭配 :host(selector) 的方式做設定

1
2
3
:host(.active){
background: red;
}

外部 html 的部分,當加上 class="active" 時,就會套用此樣式規則

1
<app-counter class="active"></app-counter>

:host-context

進一步來看,如果想要依更外層的 class 來做判斷呢? 這時候可以使用 :host-context(selector) 的方式做設定

1
2
3
:host-context(.theme-light) {
background-color: #eef;
}
1
2
3
<div class="theme-light">
<app-counter class="active"></app-counter>
</div>

套用順序

:host:host-context 的樣式會依 css 優先權規則套用。

參考資料