[译]Angular ViewEncapsulation 概念

在本文中,咱们将了解什么是视图封装(view encapsulation)?它是如何工做的?Angular视图封装有哪些类型?什么是Shadow DOM?即便浏览器不支持Shadow DOMAngular应用程序也支持样式范围吗?咱们将一一详细地看到整个问题列表!css

首先,让我向您解释用例,例如说咱们有两个组成部分:html

app.component // 1. parent component
demo.component // 2. child component
复制代码

咱们将在app组件内使用demo组件!如今,咱们在两个组件上都具备一个h1选择器以显示title,因为视图封装与样式一块儿工做,咱们在app组件中为选择器h1建立了样式。如今,当咱们在app组件内部调用demo组件时,demo组件也有了一个h1选择器。而后发生了什么? 咱们在app组件上建立的样式是否应该自动应用于demo组件的h1选择器?好吧,答案是否认的(实际上取决于您使用的是哪一种ViewEncapsulation类型),Angular应用程序使用ViewEncapuslation模式进行仿真。那是什么?因此,本篇文章提供了有关ViewEncapsulation及其如何与Angular应用程序一块儿使用的全部答案。浏览器

在开始ViewEncapusaltion如何在Angular应用程序中工做以前,咱们应该首先了解术语Shadow DOMmarkdown

Shadow DOM:

简单地说,Shadow DOM容许咱们对元素应用做用域样式,而不影响其余元素。app

详细了解Shadow DOMide

ViewEncapsulation Types:

mode value description
Emulated (default) 0 Emulate Native scoping of styles by adding an attribute containing surrogate id to the Host
Native 1 Use the native encapsulation mechanism of the renderer
None 2 Don't provide any template or style encapsulation
ShadowDom 3 Use Shadow DOM to encapsulate styles

那么,如今咱们学习一下ViewEncapsulation模式oop

1.ViewEncapsulation.None

如上所述,我建立了两个组件:学习

app.compontent.htmlspa

<h1>{{title}}</h1>
<hr>
<app-demo></app-demo>
复制代码

app.component.tscode

import { Component,ViewEncapsulation} from '@angular/core'; 复制代码@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation:ViewEncapsulation.None }) export class AppComponent { title = 'Hello from Parent'; }

app.component.css

h1{
  background: blue;
  text-transform: uppercase;
  text-align: center;
}
复制代码

demo组件中,咱们还使用h1选择器来显示title。当咱们将ViewEncapsulation模式设置为None时,相一样式的父组件将分配给子组件。在下面找到demo组件。

demo.component.html

<h1>{{title}}</h1>
复制代码

demo.component.ts

import { Component, OnInit } from '@angular/core'; 复制代码@Component({ selector: 'app-demo', templateUrl: './demo1.component.html', styleUrls: ['./demo1.component.css'] }) export class Demo1Component implements OnInit { title = 'Hello from Child'; constructor() { } ngOnInit() { } }

Output:

2. ViewEncapsulation.Emulated

如今,若是咱们将ViewEncapsulation模式更改成仿真模式,这是Angular应用程序默认提供的选项,输出将有所不一样。尽管它不使用Shadow DOM,但仍能够将样式范围限定为特定元素。并且因为它没有使用Shadow DOM,所以它仍然能够在不支持Shadow DOM的浏览器中运行。如下是更新的 app.component.ts

import { Component,ViewEncapsulation} from '@angular/core'; 复制代码@Component({ selector: 'jinal', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation:ViewEncapsulation.Emulated }) export class AppComponent { title = 'Hello from Parent'; }

咱们刚刚更新了ViewEncapsulation模式,其他一切与以前的状况相同。

正如您所见到的,咱们的组件和样式已被重写,而且为样式以及选择器添加了独特的ID类型,以在不使用Shadow DOM的状况下肯定样式的范围。这不是一个好方法吗?

它已经为咱们的样式分配了ID _ngcontent-c0,而且为咱们的app.component的h1选择器分配了相同的ID,可是对于demo组件的h1选择器,它分配了不一样的ID和_ngcontent–c1

若是对您有帮助能够关注一下。文章会继续更新下去。

相关文章
相关标签/搜索