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

前端 未结 3 1435
一整个雨季
一整个雨季 2020-12-24 07:46

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

相关标签:
3条回答
  • 2020-12-24 08:02

    ::ng-deep works for me, adding into app.component.scss:

    :host ::ng-deep .mat-card {
        background: #000 !important;
        color: #fff;
    }
    

    The documentation (https://angular.io/guide/component-styles) says:

    The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

    Use it, with precaution...

    0 讨论(0)
  • 2020-12-24 08:08

    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

    0 讨论(0)
  • 2020-12-24 08:20

    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.

    0 讨论(0)
提交回复
热议问题