如果你对子组件代码有控制权,你可以定义一个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 以获取演示。