Angular如何進(jìn)行視圖封裝?下面本篇文章給大家深入了解一下Angular Encapsulation的三種方式,希望對(duì)大家有所幫助!
在日常工作中,當(dāng)我們定義一個(gè)Component的時(shí)候,要考慮它的encapsulation封裝性,也就是說(shuō)你期望這個(gè)組件里定義的樣式是只作用于這個(gè)組件,還是想作用于全局。在 Angular 中,組件的樣式可以封裝在組件的宿主元素中,這樣它們就不會(huì)影響應(yīng)用程序的其余部分。Component 的裝飾器提供了 encapsulation 選項(xiàng),可用來(lái)控制如何基于每個(gè)組件應(yīng)用視圖封裝?!鞠嚓P(guān)教程推薦:《angular教程》】
ViewEncapsulation
Angular中有三種封裝模式,分別是ViewEncapsulation.ShadowDom,ViewEncapsulation.Emulated,ViewEncapsulation.None。
export enum ViewEncapsulation { /** * Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the * component's host element and applying the same attribute to all the CSS selectors provided * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls}. * * This is the default option. */ Emulated = 0, /** * Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls} are applicable * to any HTML element of the application regardless of their host Component. */ None = 2, /** * Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates * a ShadowRoot for the component's host element which is then used to encapsulate * all the Component's styling. */ ShadowDom = 3 }
- ViewEncapsulation.Emulated:使用墊片(shimmed) CSS 來(lái)模擬原生行為。
- ViewEncapsulation.None :使用不帶任何封裝的全局 CSS。
- ViewEncapsulation.ShadowDom:使用 Shadow DOM v1,封裝樣式。
如果沒(méi)有提供,該值就會(huì)從 CompilerOptions 中獲取它。默認(rèn)的編譯器選項(xiàng)是 ViewEncapsulation.Emulated。
如果該策略設(shè)置為 ViewEncapsulation.Emulated,并且該組件沒(méi)有指定 styles 或 styleUrls,就會(huì)自動(dòng)切換到 ViewEncapsulation.None。
有沒(méi)有發(fā)現(xiàn)枚舉類型了為什么沒(méi)有1?這個(gè)待會(huì)再說(shuō)。
ViewEncapsulation.ShadowDom
拋開(kāi)Angular中的ShadowDom的封裝,先來(lái)看一下什么是ShadowDOM吧。
Shadow DOM
Shadow DOM 允許將隱藏的 DOM 樹(shù)附加到常規(guī)的 DOM 樹(shù)中——它以 shadow root 節(jié)點(diǎn)為起始根節(jié)點(diǎn),在這個(gè)根節(jié)點(diǎn)的下方,可以是任意元素,和普通的 DOM 元素一樣。
這里,有一些 Shadow DOM 特有的術(shù)語(yǔ)需要我們了解:
- Shadow host:一個(gè)常規(guī) DOM 節(jié)點(diǎn),Shadow DOM 會(huì)被附加到這個(gè)節(jié)點(diǎn)上。
- Shadow tree:Shadow DOM 內(nèi)部的 DOM 樹(shù)。
- Shadow boundary:Shadow DOM 結(jié)束的地方,也是常規(guī) DOM 開(kāi)始的地方。
- Shadow root: Shadow tree 的根節(jié)點(diǎn)。
你可以使用同樣的方式來(lái)操作 Shadow DOM,就和操作常規(guī) DOM 一樣——例如添加子節(jié)點(diǎn)、設(shè)置屬性,以及為節(jié)點(diǎn)添加自己的樣式(例如通過(guò) element.style 屬性),或者為整個(gè) Shadow DOM 添加樣式(例如在 元素內(nèi)添加樣式)。不同的是,Shadow DOM 內(nèi)部的元素始終不會(huì)影響到它外部的元素(除了 :focus-within),這為封裝提供了便利。
我們來(lái)看一個(gè)簡(jiǎn)單的例子吧。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shadow DOM</title> <style> span{ color: green; } </style> </head> <body> <span>我是Root</span> <div id="app"></div> <script> let app = document.querySelector('#app'); let shadow1 = app.attachShadow({ mode: 'open'}); let style1 = document.createElement('style'); style1.appendChild(document.createTextNode("span{color: red;}")); shadow1.appendChild(style1); let span1 = document.createElement('span'); span1.textContent = 'I am span.'; shadow1.appendChild(span1); </script> </body> </html>
上面的例子,定義了全局span的樣式,也定義了shadowDOM里的span樣式,可以看出相互不受影響。
Angular中ShadowDOM的封裝
了解了什么是ShadowDOM后,再來(lái)看一下Angular中ShadowDOM的封裝。
Angular 使用瀏覽器內(nèi)置的 Shadow DOM API 將組件的視圖包含在 ShadowRoot(用作組件的宿主元素)中,并以隔離的方式應(yīng)用所提供的樣式。ViewEncapsulation.ShadowDom 僅適用于內(nèi)置支持 shadow DOM 的瀏覽器。并非所有瀏覽器都支持它,這就是為什么 ViewEncapsulation.Emulated 是推薦和默認(rèn)模式的原因。
比如下面的這個(gè)例子,使用ViewEncapsulation.ShadowDom。
@Component({ selector: 'user-child', templateUrl: 'UserChild.component.html', styles: [` h3{ color: red; } `], encapsulation: ViewEncapsulation.ShadowDom }) export class UserChildComponent implements OnInit { ...... }
從運(yùn)行的頁(yè)面上看到,user-child組件內(nèi)部被封裝成了一個(gè)ShadowDOM,style也被封裝在了里面,并不會(huì)對(duì)外部的樣式造成影響。
ViewEncapsulation.Emulated
Angular 會(huì)修改組件的 CSS 選擇器,使它們只應(yīng)用于組件的視圖,不影響應(yīng)用程序中的其他元素(模擬 Shadow DOM 行為)。
使用模擬視圖封裝時(shí),Angular 會(huì)預(yù)處理所有組件的樣式,以便它們僅應(yīng)用于組件的視圖。在正運(yùn)行的 Angular 應(yīng)用程序的 DOM 中,使用模擬視圖封裝模式的組件所在的元素附加了一些額外的屬性:
<hero-details _nghost-pmm-5> <h3 _ngcontent-pmm-5>Mister Fantastic</h3> <hero-team _ngcontent-pmm-5 _nghost-pmm-6> <h4 _ngcontent-pmm-6>Team</h4> </hero-team> </hero-details>
有兩種這樣的屬性:
屬性 | 詳情 |
---|---|
_nghost | 被添加到包裹組件視圖的元素中,這將是本機(jī) Shadow DOM 封裝中的 ShadowRoots。組件的宿主元素通常就是這種情況。 |
_ngcontent | 被添加到組件視圖中的子元素上,這些屬性用于將元素與其各自模擬的 ShadowRoots(具有匹配 _nghost 屬性的宿主元素)相匹配。 |
這些屬性的確切值是 Angular 的私有實(shí)現(xiàn)細(xì)節(jié)。它們是自動(dòng)生成的,你不應(yīng)在應(yīng)用程序代碼中引用它們。
它們以生成的組件樣式為目標(biāo),這些樣式會(huì)被注入到 DOM 的 部分:
[_nghost-pmm-5] { display: block; border: 1px solid black; } h4[_ngcontent-pmm-6] { background-color: white; border: 1px solid #777; }
這些樣式經(jīng)過(guò)后期處理,以便每個(gè) CSS 選擇器都使用適當(dāng)?shù)?_nghost 或 _ngcontent 屬性進(jìn)行擴(kuò)充。這些修改后的選擇器可以確保樣式以隔離和有針對(duì)性的方式應(yīng)用于組件的視圖。
<p>child works!</p>
p{ color: green; }
@Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'], encapsulation: ViewEncapsulation.Emulated }) export class ChildComponent implements OnInit { ...... }
ViewEncapsulation.Emulated 設(shè)置的結(jié)果是沒(méi)有 Shadow DOM,但是通過(guò) Angular 提供的樣式包裝機(jī)制來(lái)封裝組件,使得組件的樣式不受外部影響。雖然樣式仍然是應(yīng)用到整個(gè) document,但 Angular 為 p創(chuàng)建了一個(gè) [_ngcontent-oow-c11] 選擇器??梢钥闯?,我們?yōu)榻M件定義的樣式,被 Angular 修改了。簡(jiǎn)單來(lái)說(shuō),盡管是也是全局樣式,但是由于自動(dòng)選擇器的原因,并不會(huì)影響其他組件的樣式。如果手動(dòng)在其他元素上也添加這個(gè)屬性,則樣式也會(huì)應(yīng)用到這元素上。
ViewEncapsulation.None
Angular 不應(yīng)用任何形式的視圖封裝,這意味著為組件指定的任何樣式實(shí)際上都是全局應(yīng)用的,并且可以影響應(yīng)用程序中存在的任何 HTML 元素。這種模式本質(zhì)上與將樣式包含在 HTML 本身中是一樣的。
parent:
<p #caption>parent works!{{count}}</p> <p #caption>第一個(gè):{{count}}</p> <span class="red-font">parent</span> <app-child></app-child>
child:
<div style="border: 1px solid green;"> <p>child works!</p> <span class="red-font">Child</span> </div>
p{ color: green; } .red-font { color: red; }
@Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'], encapsulation: ViewEncapsulation.None }) export class ChildComponent implements OnInit { ...... }
被廢棄的Native
在Angular2中使用ViewEncapsulation.Native。
@Component({ ..., encapsulation: ViewEncapsulation.Native }) export class UserComponent {
ViewEncapsulation.Native 設(shè)置的結(jié)果是使用原生的 Shadow DOM 特性。Angular 會(huì)把組件按照瀏覽器支持的 Shadow DOM 形式渲染。其實(shí)這種就是后來(lái)的ViewEncapsulation.ShadowDom。
總結(jié)
我們介紹了Angular視圖封裝的三種方式,各自的特點(diǎn),日常工作中要根據(jù)特定的場(chǎng)景去選擇哪種封裝方式。