从宿主组件角度覆盖子组件样式的正确方法 [英] Right way to override child component style from host component angular
问题描述
从主机组件覆盖子组件样式的正确方法是什么.我尝试使用encapsulation: ViewEncapsulation.None
,但是我需要在style.sass文件中而不是主机组件中写入替代内容.什么是 stackblitz >
What is the right way to override child component style from host component. I tried using encapsulation: ViewEncapsulation.None
but i need to write the override stuff in style.sass file rather than host component. What should be the stackblitz
推荐答案
如果您可以控制子组件代码,则可以定义customStyle
输入属性:
If you have control on the child component code, you can define a customStyle
input property:
@Input() customStyle: {};
<div class="child-div" [ngStyle]="customStyle">I am the child</div>
并从父组件传递它:
<app-child [customStyle]="style1"></app-child>
style1 = {
backgroundColor: "red",
height: "150px"
}
有关演示,请参见此stackblitz .
类似的技术可以允许将特定的样式属性传递给子组件:
A similar technique can allow to pass a specific style attribute to the child component:
@Input() backgroundColor: string;
<div class="child-div" [style.background-color]="backgroundColor">I am the child</div>
来自父组件:
<app-child backgroundColor="red"></app-child>
请参见此stackblitz 一个演示.
否则,在Angular提出替代方法之前,您可以使用::ng-deep
Otherwise, until an alternative method is proposed by Angular, you can use the ::ng-deep
shadow-piercing descendant combinator to modify the child component styling from the parent CSS:
:host ::ng-deep .parent .child-div {
background-color: lime;
height: 200px;
}
请参见此stackblitz 一个演示.
这篇关于从宿主组件角度覆盖子组件样式的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!