Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

angular2viewencapsulation - 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. What should be the stackblitz

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...