在本文中,咱們將瞭解什麼是視圖封裝(view encapsulation)?它是如何工做的?Angular
視圖封裝有哪些類型?什麼是Shadow DOM
?即便瀏覽器不支持Shadow DOM
,Angular
應用程序也支持樣式範圍嗎?咱們將一一詳細地看到整個問題列表!css
首先,讓我向您解釋用例,例如說咱們有兩個組成部分:html
app.component // 1. parent component
demo.component // 2. child component
複製代碼
咱們將在app
組件內使用demo
組件!如今,咱們在兩個組件上都具備一個h1
選擇器以顯示title
,因爲視圖封裝與樣式一塊兒工做,咱們在app
組件中爲選擇器h1
建立了樣式。如今,當咱們在app
組件內部調用demo
組件時,demo
組件也有了一個h1
選擇器。而後發生了什麼? 咱們在app
組件上建立的樣式是否應該自動應用於demo
組件的h1
選擇器?好吧,答案是否認的(實際上取決於您使用的是哪一種ViewEncapsulation
類型),Angular
應用程序使用ViewEncapuslation
模式進行仿真。那是什麼?因此,本篇文章提供了有關ViewEncapsulation
及其如何與Angular
應用程序一塊兒使用的全部答案。web
在開始ViewEncapusaltion
如何在Angular
應用程序中工做以前,咱們應該首先了解術語Shadow DOM
。瀏覽器
簡單地說,Shadow DOM容許咱們對元素應用做用域樣式,而不影響其餘元素。app
mode | value | description |
---|---|---|
Emulated (default) | 0 | Emulate Native scoping of styles by adding an attribute containing surrogate id to the Host |
Native | 1 | Use the native encapsulation mechanism of the renderer |
None | 2 | Don't provide any template or style encapsulation |
ShadowDom | 3 | Use Shadow DOM to encapsulate styles |
那麼,如今咱們學習一下ViewEncapsulation模式ide
如上所述,我建立了兩個組件:學習
app.compontent.htmlurl
<h1>{{title}}</h1>
<hr>
<app-demo></app-demo>
複製代碼
app.component.tsspa
import { Component,ViewEncapsulation} from '@angular/core'; 複製代碼@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation:ViewEncapsulation.None }) export class AppComponent { title = 'Hello from Parent'; } 複製代碼
app.component.css
h1{
background: blue;
text-transform: uppercase;
text-align: center;
}
複製代碼
在demo
組件中,咱們還使用h1
選擇器來顯示title
。當咱們將ViewEncapsulation
模式設置爲None
時,相一樣式的父組件將分配給子組件。在下面找到demo
組件。
demo.component.html
<h1>{{title}}</h1>
複製代碼
demo.component.ts
import { Component, OnInit } from '@angular/core'; 複製代碼@Component({ selector: 'app-demo', templateUrl: './demo1.component.html', styleUrls: ['./demo1.component.css'] }) export class Demo1Component implements OnInit { title = 'Hello from Child'; constructor() { } ngOnInit() { } } 複製代碼
如今,若是咱們將ViewEncapsulation
模式更改成仿真模式,這是Angular
應用程序默認提供的選項,輸出將有所不一樣。儘管它不使用Shadow DOM
,但仍能夠將樣式範圍限定爲特定元素。並且因爲它沒有使用Shadow DOM
,所以它仍然能夠在不支持Shadow DOM
的瀏覽器中運行。如下是更新的 app.component.ts
import { Component,ViewEncapsulation} from '@angular/core'; 複製代碼@Component({ selector: 'jinal', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation:ViewEncapsulation.Emulated }) export class AppComponent { title = 'Hello from Parent'; } 複製代碼
咱們剛剛更新了ViewEncapsulation模式,其他一切與以前的狀況相同。
正如您所見到的,咱們的組件和樣式已被重寫,而且爲樣式以及選擇器添加了獨特的ID類型,以在不使用Shadow DOM
的狀況下肯定樣式的範圍。這不是一個好方法嗎?
它已經爲咱們的樣式分配了ID _ngcontent-c0
,而且爲咱們的app.component
的h1選擇器分配了相同的ID,可是對於demo組件的h1選擇器,它分配了不一樣的ID和_ngcontent–c1
。
若是對您有幫助能夠關注一下。文章會繼續更新下去。