Angular2 styling issues caused by DOM attributes _ngcontent-* vs. _nghost-*

27,112

Solution 1

Well,

I found the answer myself. Using the default settings, you must not supply the wrapping my-comp element selector in the components css.

Instead use the * element selector to affect all elements nested in my-comp. Otherwise, angular will treat the my-comp selector as an additional element and thus add the _ng-content-* attribute, which of course is not present in the DOM.

Another option is to disable ViewEncapsulation for your component - be aware that it just affects the component my-comp

import {Component, ViewEncapsulation} from 'angular2/core'

@Component({
  selector: 'my-comp',
  encapsulation: ViewEncapsulation.None,
  ...
});

https://egghead.io/lessons/angular-2-controlling-how-styles-are-shared-with-view-encapsulation explains the three different settings modes perfectly.

Solution 2

update

It's ::ng-deep since a while.
See also the comments below.

original

You didn't provide too much details where you add your styles and what elements you target with the selectors.

The "official" way if you want styles to cross element boundaries is to use >>> like

:host >>> h1 {
  background-color: red;
}
  • :host targets the current element.
  • >>> (or /deep/) makes Angular ignore _nghost-xxx attributes which is used for component style encapsulation emulation.

See also Styles in component for D3.js do not show in angular 2

Share:
27,112
wzr1337
Author by

wzr1337

Updated on July 09, 2022

Comments

  • wzr1337
    wzr1337 almost 2 years

    I have an issue with scss and the cli: angular adds an attribute _nghost-fyw-1 to the apps tag (component) during runtime. at the same time it adds an attribute selector to my css called _ngcontent-fyw-1 which of course won't work.

    Do you have an idea how i could change this behavior/ avoid it?

    PS: it also applies to regular css.

    my components .scss file looks like this:

    my-comp {
      h1 {
        background-color: red;
      }
    }