Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to propagate css properties to inner Angular components and children?

Tags:

css

angular

I have an Angular 2 app with custom HTML elements that looks like this:

<custom1>
 <div id="div1">
  <div id="div2"></div>
  <custom2>
   <div id="div3"></div>
  </custom2>
 </div>
</custom1>

In component custom1 I have this css:

div {
 border-style: solid;
}

This style works well for the elements div1 and div2, while it is not propagated to element div3.

How to propagate CSS properties of custom1 into custom2 without writing a specific CSS for custom2 ?

In case it is relevant: custom1 is included into a Bootstrap grid container.

like image 875
ThCollignon Avatar asked Oct 19 '25 06:10

ThCollignon


1 Answers

You can set the View Encapsulation to None on your custom1 component:

@Component({
    templateUrl: './custom1.component.html' ,
    styleUrls: ['./custom1.component.css'],
    encapsulation: ViewEncapsulation.None,
})

Snippet from the link I provided:

Component CSS styles are encapsulated into the component's view and don't affect the rest of the application.

To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes:

Native view encapsulation uses the browser's native shadow DOM implementation (see Shadow DOM on the MDN site) to attach a shadow DOM to the component's host element, and then puts the component view inside that shadow DOM. The component's styles are included within the shadow DOM.

Emulated view encapsulation (the default) emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view. For details, see Appendix 1.

None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

like image 91
Andrei Matracaru Avatar answered Oct 21 '25 21:10

Andrei Matracaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!