从主机组件覆盖子组件样式的正确方法 angular
Right way to override child component style from host component angular
从宿主组件覆盖子组件样式的正确方法是什么。我尝试使用 encapsulation: ViewEncapsulation.None
但我需要在 style.sass 文件而不是主机组件中编写覆盖内容。 stackblitz
应该是什么
如果您可以控制子组件代码,您可以定义一个 customStyle
输入 属性:
@Input() customStyle: {};
<div class="child-div" [ngStyle]="customStyle">I am the child</div>
并从父组件传过来:
<app-child [customStyle]="style1"></app-child>
style1 = {
backgroundColor: "red",
height: "150px"
}
有关演示,请参阅 this stackblitz。
类似的技术可以允许将特定样式属性传递给子组件:
@Input() backgroundColor: string;
<div class="child-div" [style.background-color]="backgroundColor">I am the child</div>
来自父组件:
<app-child backgroundColor="red"></app-child>
有关演示,请参阅 this stackblitz。
否则,在 Angular 提出替代方法之前,您可以使用 ::ng-deep
shadow-piercing descendant combinator 从父组件 CSS 修改子组件样式:
:host ::ng-deep .parent .child-div {
background-color: lime;
height: 200px;
}
有关演示,请参阅 this stackblitz。
我的 "way" 正在使用 viewEncapsulation.None,重要的是将 class 添加到 child。
forked stackblitz's Connors
//The parent
.child1 .child-div {
background-color: lime!important;
height: 200px!important;
}
<div style="text-align: center;" class='parent'>Hi I am the app-root and I contain child-comp!
<app-child class="child1"></app-child>
<app-child ></app-child>
</div>
从宿主组件覆盖子组件样式的正确方法是什么。我尝试使用 encapsulation: ViewEncapsulation.None
但我需要在 style.sass 文件而不是主机组件中编写覆盖内容。 stackblitz
如果您可以控制子组件代码,您可以定义一个 customStyle
输入 属性:
@Input() customStyle: {};
<div class="child-div" [ngStyle]="customStyle">I am the child</div>
并从父组件传过来:
<app-child [customStyle]="style1"></app-child>
style1 = {
backgroundColor: "red",
height: "150px"
}
有关演示,请参阅 this stackblitz。
类似的技术可以允许将特定样式属性传递给子组件:
@Input() backgroundColor: string;
<div class="child-div" [style.background-color]="backgroundColor">I am the child</div>
来自父组件:
<app-child backgroundColor="red"></app-child>
有关演示,请参阅 this stackblitz。
否则,在 Angular 提出替代方法之前,您可以使用 ::ng-deep
shadow-piercing descendant combinator 从父组件 CSS 修改子组件样式:
:host ::ng-deep .parent .child-div {
background-color: lime;
height: 200px;
}
有关演示,请参阅 this stackblitz。
我的 "way" 正在使用 viewEncapsulation.None,重要的是将 class 添加到 child。 forked stackblitz's Connors
//The parent
.child1 .child-div {
background-color: lime!important;
height: 200px!important;
}
<div style="text-align: center;" class='parent'>Hi I am the app-root and I contain child-comp!
<app-child class="child1"></app-child>
<app-child ></app-child>
</div>