Angular2 的 View Encapsulation(樣式封裝)

Angular2 的 View Encapsulation(樣式封裝)

angular2 版本:2.4.8, 測試代碼地址

Shadow Dom

開始之間,建議先了解下Shadow Dom 方面的知識(shí)

View Encapsulation 的種類

  • ViewEncapsulation.None - 沒有Shadow Dom,樣式?jīng)]有封裝,全局可以使用。
  • ViewEncapsulation.Emulated - angular2的默認(rèn)值,模仿 Shadow Dom,通過在標(biāo)簽上增加標(biāo)識(shí),來固定樣式的作用域。
  • ViewEncapsulation.Native - 使用原生的Shadow Dom。

ViewEncapsulation.None

@Component({
    selector: 'component-one',
    template: `

      <div class="red"></div>
      
      <br>
      
      <div class="green"></div>
      
      <br>
      
      <div class="blue"></div>
    `,
    styles:[`
        .green{
          background-color: green;
          width:20px;
          height: 20px;
        }
    `],
    encapsulation:ViewEncapsulation.None
})

生成的<head>標(biāo)簽中的<style>中的樣式是沒有作用域的。和普通在<head>標(biāo)簽中的<style>中引用的標(biāo)簽一樣,作用域全局。

ViewEncapsulation.Emulated

@Component({
  selector: 'app-root',
  template:`
    app-component
    <div class="red"></div>    
    <br>   
    <div class="green"></div>   
    <br>    
    <div class="blue"></div>    
    <br>
    <br>
    component-one
    <component-one></component-one>    
    component-two
    <component-two></component-two>
  `,
  styles:[`
    .red{
      background-color: red;
      height: 20px;
      width: 20px;
    }

  `]
})

生成的<head>標(biāo)簽中的<style>中的樣式是有作用域的。[ ]方括號內(nèi)的表明了作用域。這是css選擇器的一種。

.red[_ngcontent-fnb-0]{
  background-color: red;
  height: 20px;
  width: 20px;
}

ViewEncapsulation.Native

@Component({
  selector: 'component-two',
  template: `

    <div class="red"></div>
    
    <br>
    
    <div class="green"></div>
    
    <br>
    
    <div class="blue"></div>
    
    `,
  styles:[`
      .blue{
        background-color: blue;
        width: 20px;
        height: 20px;
      }
  `],
  encapsulation:ViewEncapsulation.Native
})

不會(huì)再<head>標(biāo)簽中的<style>中生成樣式,所以也無法作用與其他組件。實(shí)際效果著這樣的:

總結(jié)

  • 如果在子組件中使用的css樣式不想影響全局,可以不用設(shè)置(默認(rèn)ViewEncapsulation.Emulated)。
  • 可以在main.ts設(shè)置 ViewEncapsulation.None 將引用css設(shè)置為影響全局,一般用來設(shè)置一個(gè)網(wǎng)站的字體整體樣式什么的。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在線閱讀 http://interview.poetries.top[http://interview.poetr...
    前端進(jìn)階之旅閱讀 115,559評論 24 450
  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 14,154評論 1 92
  • <a name='html'>HTML</a> Doctype作用?標(biāo)準(zhǔn)模式與兼容模式各有什么區(qū)別? (1)、<...
    clark124閱讀 3,832評論 1 19
  • 引導(dǎo) 這是一個(gè)很簡單的話題,但是你很難在搜索到一篇比較完整的介紹它的文章,或者說單純的告訴你 ViewEncaps...
    cipchk閱讀 1,246評論 0 3
  • 目錄 四月,最喜桃花盛開的樣子。 我置身桃林,流連忘返, 是思念,是留戀。 想那十里桃花是何等的壯觀, 也只有超凡...
    雪兒葉子閱讀 744評論 0 3

友情鏈接更多精彩內(nèi)容