Angular2 的 View Encapsulation(样式封装)css样式的通用性以及私有性

Angular2 的 View Encapsulation(样式封装)

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

Shadow Dom

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

View Encapsulation 的种类

  • ViewEncapsulation.None - 没有Shadow Dom,样式没有封装,全局可以使用。
  • ViewEncapsulation.Emulated - angular2的默认值,模仿 Shadow Dom,通过在标签上增加标识,来固定样式的作用域。
  • 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>标签中的<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>中生成样式,所以也无法作用与其他组件。实际效果着这样的:



作者:CK110
链接:https://www.jianshu.com/p/b63c6218fc44
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值