Angular2 的 View Encapsulation(样式封装)

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>中生成样式,所以也无法作用与其他组件。实际效果着这样的:

总结

  • 如果在子组件中使用的css样式不想影响全局,可以不用设置(默认ViewEncapsulation.Emulated)。
  • 可以在main.ts设置 ViewEncapsulation.None 将引用css设置为影响全局,一般用来设置一个网站的字体整体样式什么的。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在线阅读 http://interview.poetries.top[http://interview.poetr...
    前端进阶之旅阅读 114,857评论 24 450
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,815评论 1 92
  • <a name='html'>HTML</a> Doctype作用?标准模式与兼容模式各有什么区别? (1)、<...
    clark124阅读 3,570评论 1 19
  • 引导 这是一个很简单的话题,但是你很难在搜索到一篇比较完整的介绍它的文章,或者说单纯的告诉你 ViewEncaps...
    cipchk阅读 1,225评论 0 3
  • 目录 四月,最喜桃花盛开的样子。 我置身桃林,流连忘返, 是思念,是留恋。 想那十里桃花是何等的壮观, 也只有超凡...
    雪儿叶子阅读 710评论 0 3