我创建了一个模态组件,它可以投影3个部分:header,body和footer。
modal.component.html
<div>
<ng-content select="section[modal-header]"></ng-content>
<ng-content select="section[modal-body]"></ng-content>
<ng-content select="section[modal-footer]"></ng-content>
</div>
因此,用法:
<modal-component>
<section modal-header>Header</section>
<section modal-body>Body</section>
<section modal-footer>Footer</section>
</modal-component>
我想设置header
的样式。因此:
modal.component.scss
:host([modal-header]) { font-weight: bold; }
这不起作用。我错过了什么吗?
答案 0 :(得分:5)
组件样式通常仅适用于组件自己的模板中的HTML。
使用/ deep / shadow-penetcing后代组合子将样式向下强制通过子组件树到所有子组件视图中。 / deep / combinator适用于任何深度的嵌套组件,它适用于视图子组件和组件的内容子组件。
:host /deep/ [modal-header] { font-weight: bold; }
在角度文档中,他们提到/ deep /已弃用,因此您可以使用 :: NG-深
:host ::ng-deep [modal-header] { font-weight: bold; }
答案 1 :(得分:1)
Angular官方文档中的报价
不推荐使用穿刺后代组合器,并且支持 从主要的浏览器和工具中删除。因此,我们计划放弃 支持Angular(适用于/ deep /,>>>和:: ng-deep的全部3种)。
另一种选择是结合使用@Component
装饰器encapsulation
属性和使用@HostBinding
向主机添加类的方法
encapsulation: ViewEncapsulation.None
。这将确保没有样式封装,并且样式在全局范围内有效。要封装样式,请将custon CSS类添加到子组件的宿主中,作为
@HostBinding('class.custContainerClass') containerClass: boolean = true;
在子组件中将样式写为
.custContainerClass .projectedElement { }
演示在https://stackblitz.com/edit/angular-add-styles-to-projected-content
答案 2 :(得分:-1)
我认为您应该在使用modal-component
的组件中添加css
就像如果您在modal-component
中使用app.component.html
,那么您应该在app.component.scss
中写CSS,而无需 host 和 ng deep < / p>
[modal-header] {
font-weight: bold;
}
实际上,有两个原因,一个是因为您可能会在两个不同的组件中使用modal-component
,并且希望各节使用不同的CSS。
第二点是您应该在实际内容所在的地方写css。
如果您仍然想在modal-component
中编写CSS代码,则应创建父容器来保存该内容,例如:
<div class="header">
<ng-content select="section[modal-header]"></ng-content>
</div>
<ng-content select="section[modal-body]"></ng-content>
<ng-content select="section[modal-footer]"></ng-content>
以及您的modal.component.scss
文件
.header {
font-weight: bold
}
因为ng-content
被新模板替换,所以您需要父容器。