9

从主机组件覆盖子组件样式的正确方法是什么。我尝试使用 encapsulation: ViewEncapsulation.None,但我需要在 style.sass 文件而不是主机组件中编写覆盖内容。堆栈闪电战应该是什么

4

2 回答 2

19

如果您可以控制子组件代码,则可以定义一个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"
}

有关演示,请参阅此 stackblitz


类似的技术可以允许将特定的样式属性传递给子组件:

@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 穿透阴影的后代组合器从父 CSS 修改子组件样式:

:host ::ng-deep .parent .child-div {
  background-color: lime;
  height: 200px;
}

有关演示,请参阅此 stackblitz

于 2019-01-23T14:03:18.780 回答
2

我的“方式”是使用 viewEncapsulation.None,重要并向孩子添加课程。分叉的stackblitz 的 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>
于 2019-01-23T15:33:02.983 回答