一、视图封装模式encapsulation

在组件的元数据设置encapsulation,可以分别控制每个组件的封装模式。

三个可选的封装模式:

  • ShadowDom: 任何外部样式都无法进来,组件样式也出不去
  • Emulated: 只有全局样式能进来,其他样式无法进来,组件样式也出不去(默认值)
  • None: 任何样式都能进来,组件的样式也都能出去

全局样式文件styles.less

/* You can add global styles to this file, and also import other style files */
.global-color {
    color: red;
}

组件文件home.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `
    <div class="global-color">全局样式</div>
    <div class="local-color">组件样式</div>
  `,
  styles: [`
    .local-color {
      color: blue;
    }
  `],
  encapsulation: ViewEncapsulation.ShadowDom,		//配置视图封装模式
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

1、ShadowDom

组件相当于是隔离状态,不受外界样式的影响。

encapsulation: ViewEncapsulation.ShadowDom

2、Emulated

组件相当于是半隔离状态,受全局样式的影响。

当选择器相同且选择器优先级相同时,组件内部样式的优先级大于全局样式的优先级。

encapsulation: ViewEncapsulation.ShadowDom

3、None

组件相当于是暴露状态,受所有样式的影响。

encapsulation: ViewEncapsulation.None

二、查看生成的 CSS

生成出的属性分为两种:

一个元素在原生封装方式下可能是 Shadow DOM 的宿主,在这里被自动添加上一个 _nghost 属性。 这是组件宿主元素的典型情况。

组件视图中的每一个元素,都有一个 _ngcontent 属性,它会标记出该元素属于哪个宿主的模拟 Shadow DOM