Angular Component 處理styles有三種模式
1. ViewEncapsulation.None: 適用於全部頁面(No Shadow DOM)
2. ViewEncapsulation.Native: 僅套用於Shadow DOM自己本身
3. ViewEncapsulation.Emulated: 預設行為。 會自動將每個component給予一個名稱,讓各compoent裡面的style會各自獨立
先來看第1,2種,看看style會被放在哪一個位置
- ViewEncapsulation.None
1 2 3 4 5 6 7 8 9 10 11
| @Component({ selector: 'ck-book', template: require('./book.html'), styles: [` h3 { color: red } `], encapsulation: ViewEncapsulation.None }) export class CkBookPage {}
|

2.ViewEncapsulation.Native
1 2 3 4 5 6 7 8 9 10 11
| @Component({ selector: 'ck-book', template: require('./book.html'), styles: [` h3 { color: red } `], encapsulation: ViewEncapsulation.Native }) export class CkBookPage {}
|

注意到ViewEncapsulation.Native將ViewEncapsulation.None的和本身定義的Style都包含在Shadow DOM裡面,這表示該Componenet與外面已經分開了. 本身所定義的css樣式不會影響到別人了
- ViewEncapsulation.Emulated為預設行為,會自動將每個Component給予一個名稱,然後在產生html時會將各Componet裡
定義的style加上該名稱,讓css不會互相影響
1 2 3 4 5 6 7 8 9 10
| @Component({ selector: 'ck-book', template: require('./book.html'), styles: [` h3 { color: red } `], encapsulation: ViewEncapsulation.Emulated })
|
1 2 3 4 5 6
| <style>h3[_ngcontent-jfs-3] { color: red }</style> <div _ngcontent-jfs-3 class="clearfix mx-auto col-8"> <h3 _ngcontent-jfs-3>Booking</h3> ....
|

參考