Angular2 的 View Encapsulation(样式

2017-02-24  本文已影响3213人  CK110

Angular2 的 View Encapsulation(样式封装)

angular2 版本:2.4.8, 测试代码地址

Shadow Dom

开始之间,建议先了解下Shadow Dom 方面的知识

View Encapsulation 的种类

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>标签中的<style>中的样式是没有作用域的。和普通在<head>标签中的<style>中引用的标签一样,作用域全局。

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>标签中的<style>中的样式是有作用域的。[ ]方括号内的表明了作用域。这是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
})

不会再<head>标签中的<style>中生成样式,所以也无法作用与其他组件。实际效果着这样的:

总结

上一篇 下一篇

猜你喜欢

热点阅读