以下所有代码的演示地址:
戳这里 => demo展示
组件样式独立
组件之间的样式并不互相影响,也就是说,在A组件编写的样式不会渲染到B组件。
app.component.html
@Component({
selector: 'my-app',
template: `
<h1>我是父组件的h1</h1>
<detail></detail>
`,
styles:[`
h1{ color:red; }
`]
})
detail.component.html
@Component({
selector: 'detail',
template: ['<h1>我是detail组件的h1</h1>']
})
渲染宿主标签样式
一般情况下,组件@Component的样式是渲染在template上的,那么如果想给宿主标签,即selector标签写上样式,应该怎么写呢?
官方文档给出了答案 —— :host
demo:给detail标签写flex布局样式
@Component({
selector: 'detail',
template: `
<h1>我是detail组件的h1</h1>
`,
styles:[`
:host{
display:flex;
}
`]
})
基于外部组件渲染样式
有的时候,需要基于外部组件来渲染样式,比如:
在外部组件li的class值为active的时候才将组件文字渲染成蓝色。
这个时候,我们就需要 —— :host-context(.xxx)
demo:
:host-context(.active) h1{
color:blue;
}
意思就是:当外部组件中类名值为”active”时,其h1的样式渲染为蓝色。
而需要注意的是,以上情况对组件投影内容是无效的!!!
渲染投影内容样式
我觉得这算是一个终极用法了吧。虽然目前Angular已经废除了这种写法,但是在项目中为了渲染组件投影内容样式,不得不使用这种写法,因此,在这里也分享一下。
渲染投影内容样式 —— :host /deep/
demo:对<ng-content></ng-content>
投影内容进行渲染
:host /deep/ p {
font-size:18px;
color:gray;
}
对于投影内容,不管是ng-content
,还是ng-container
,都是有效的。不过需要明确的是,这个方法已经被Angular废弃,所以还是尽量少用!