Angular2 的 View Encapsulation(樣式封裝)
angular2 版本:2.4.8, 測試代碼地址
Shadow Dom
開始之間,建議先了解下Shadow Dom 方面的知識(shí)
View Encapsulation 的種類
- ViewEncapsulation.None - 沒有Shadow Dom,樣式?jīng)]有封裝,全局可以使用。
- ViewEncapsulation.Emulated - angular2的默認(rèn)值,模仿 Shadow Dom,通過在標(biāo)簽上增加標(biāo)識(shí),來固定樣式的作用域。
- 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>標(biāo)簽中的<style>中的樣式是沒有作用域的。和普通在<head>標(biāo)簽中的<style>中引用的標(biāo)簽一樣,作用域全局。
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>標(biāo)簽中的<style>中的樣式是有作用域的。[ ]方括號內(nèi)的表明了作用域。這是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
})
不會(huì)再<head>標(biāo)簽中的<style>中生成樣式,所以也無法作用與其他組件。實(shí)際效果著這樣的:
總結(jié)
- 如果在子組件中使用的css樣式不想影響全局,可以不用設(shè)置(默認(rèn)ViewEncapsulation.Emulated)。
- 可以在main.ts設(shè)置 ViewEncapsulation.None 將引用css設(shè)置為影響全局,一般用來設(shè)置一個(gè)網(wǎng)站的字體整體樣式什么的。