Right way to override child component style from host component angular

喜欢而已 提交于 2019-11-27 08:05:29

问题


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


回答1:


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>

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:

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

See this stackblitz for a demo.




回答2:


My "way" is using viewEncapsulation.None, important and add class to the child. 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>


来源:https://stackoverflow.com/questions/54328837/right-way-to-override-child-component-style-from-host-component-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!