目前為止都還沒仔細談過 Component 的樣式
加上 Style 的方法
<button type="button">
<p style="color:red;">Press me</p>
</button>
上面這麼多方法,光看就眼花了,來看一個實際的例子:
我們會針對 Reload 按鈕的樣式(背景色)作調整,來看上面的機制是怎麼運作的:
首先,先在 navbar.component.css 加上以下的 CSS
.btn { background-color: #e32738; }
接著我們調整 Navbar @Component 的 metadata,加上 styles 如下:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css'],
styles: [`.btn { background-color: #999999; }`]
})
export class NavbarComponent {
constructor() { }
@Output() onRefresh: EventEmitter<null> = new EventEmitter<null>();
refresh() {
this.onRefresh.emit();
}
}
還沒結束呢,我們接著打開 navbar.component.html,並加入以下:
<style>.btn { background-color: #3274b8; }</style>
最後最後,如果直接在 button 上加 style 如下:
<button class="btn btn-success"
type="button"
style="background-color:#8616f6"
(click)="refresh()">Reload
</button>
所以說,統一樣式的設定方式是很重要的
Encapsulation modes(封裝模式)
上面介紹了那麼多種調整樣式的方式,但最後它會如何作用在 HTML 上,其實是看封裝模式是設定成哪種來決定,在 Angular 共有三種:
所以說那個醬汁呢?
模式要設定在哪裡?其實又是我們的老朋友 @Component,其中有一個屬性叫 encapsulation,記得要 import ViewEncapsulation
以 MetricComponent 為例,假設我任性想沿用全域的樣式就好,可以如下:
import { ChangeDetectionStrategy, Component, Input, OnChanges, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-metric',
templateUrl: './metric.component.html',
styleUrls: ['./metric.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None
})
export class MetricComponent implements OnChanges {
@Input('used') value: number = 0;
@Input('available') max: number = 100;
ngOnChanges(changes) {
if(changes.value && isNaN(changes.value.currentValue)) this.value = 0;
if(changes.max && isNaN(changes.max.currentValue)) this.max = 100;
}
isDanger() {
return this.value / this.max > 0.7;
}
}
小結: