简体   繁体   English

从宿主组件角度覆盖子组件样式的正确方法

[英]Right way to override child component style from host component angular

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. 我尝试使用encapsulation: ViewEncapsulation.None但我需要在style.sass文件中而不是主机组件中写入替代内容。 What should be the stackblitz 什么是堆叠闪电战

If you have control on the child component code, you can define a customStyle input property: 如果您可以控制子组件代码,则可以定义customStyle输入属性:

@Input() customStyle: {};
<div class="child-div" [ngStyle]="customStyle">I am the child</div>

and pass it from the parent component: 并从父组件传递它:

<app-child [customStyle]="style1"></app-child>
style1 = {
  backgroundColor: "red",
  height: "150px"
}

See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战


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>

from the parent component: 来自父组件:

<app-child backgroundColor="red"></app-child>

See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战


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: 否则,直到Angular提出了另一种方法,您可以使用::ng-deep -sharing-piercing后代组合器来修改父CSS的子组件样式:

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

See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战

My "way" is using viewEncapsulation.None, important and add class to the child. 我的“方法”是使用viewEncapsulation.None,不重要,并向孩子添加类。 the 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM