Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

sass

angular

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;
  }
}
like image 839
wzr1337 Avatar asked Jun 07 '16 21:06

wzr1337


2 Answers

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.

like image 65
wzr1337 Avatar answered Nov 08 '22 20:11

wzr1337


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

like image 33
Günter Zöchbauer Avatar answered Nov 08 '22 20:11

Günter Zöchbauer