美文网首页
angular ViewEncapsulation

angular ViewEncapsulation

作者: 云上笔记 | 来源:发表于2021-03-03 18:36 被阅读0次

    ViewEncapsulation 用于定义组件的样式封装选项,当你新建了一个组件时,可以通过配置这个选项来设置该组件的样式如何生效

    ViewEncapsulation 的三个可选值

    Emulate可进不出,默认项,公共样式可作用于该组件,但该组件样式不会影响其他组件;
    None可进可出,当前组件的样式作用于全局,会影响其他组件样式;
    ShadowDom不进不出,使用shadowDom封装样式,公共样式不能作用于该组件,该组件的样式也不会影响其他组件,可以把它看成一个独立的html;

    ViewEncapsulation.None 的用法

    // ShadowNoteComponent
    import { Component, OnInit, ViewEncapsulation } from '@angular/core';
    
    @Component({
      selector: 'app-shadow-note',
      template: `
        <p class="title">
          ShadowNoteComponent ==> ViewEncapsulation.None
        </p>
      `,
      styles: [`
        .title{
          color: skyblue;
          font-size: 18px;
          font-weight: bold;
        }
      `],
      encapsulation: ViewEncapsulation.None
    })
    
    // AppComponent
    @Component({
      selector: 'app-root',
      template: `
         <p class="title">AppComponent ==> ViewEncapsulation.Emulate</p>
         <app-shadow-note></app-shadow-note>
      `,
      styles: [`
        .title{
          color: red;
          font-size: 14px;
        }
      `],
    })
    

    最后的效果如下


    图片.png

    可以看到,AppComponent 的p标签上出现了两个 title 样式,分别是 AppComponent、 ShadowNoteComponent 组件中定义的,由于 ShadowNoteComponent 组件设置了ViewEncapsulation.None,使得该组件内样式作用于全局,同时,angular 为 AppComponent 中的 title 样式创建了一个 [_ngcontent-qda-c0] 选择器,其样式权重大于另一个 .title,最终表现为红色14号粗体。

    个人感觉 ViewEncapsulation.None 最好慎用

    相关文章

      网友评论

          本文标题:angular ViewEncapsulation

          本文链接:https://www.haomeiwen.com/subject/grdqqltx.html