How to style encapsulated child components in angular?

Viewed 63

How to style encapsulated child components in angular?

Following are the child and parent components with view encapsulation enabled.

** child

//template
<div class="child-container"> </div>

// class
@Component({
  selector: "app-child",
  templateUrl: "./child.component.html",
  styleUrls: ["./child.component.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})
** parent

//template
<div class="parent-container"> </div>

// class
@Component({
  selector: "app-parent",
  templateUrl: "./parent.component.html",
  styleUrls: ["./parent.component.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})

How can I select a particular class inside the Child component from the parent component's stylesheet and change it's style?

** parent

//template
<div class="parent-container">
<app-child></app-child>
 </div>

// class
@Component({
  selector: "app-parent",
  templateUrl: "./parent.component.html",
  styleUrls: ["./parent.component.css"],
  encapsulation: ViewEncapsulation.ShadowDom
})

//styles
app-child {
.child-container {
background colour: red;
}
}

Currently when I try to select a class from the child component, I'm not being able to override it's styles. Please help!

Remember that ViewEncapsulation.ShadowDom is required for my used cased. So we have to keep that in mind.

2 Answers

css variables are accessible through the shadow dom.. so in your app-parent component scss, you should be able to do something like

--child-comp-background: red;

and in your app child component scss,

background-color: var(--child-comp-background, white) //white is a default incase the variable isnt defined or passed down from the parent

you can use :host-context() to do that

:host-context(.parent-container) .child-container{
...style here
}

Here the demo: Demo

Related