1

I have a "Sidenav" component in which I use svg's as menu icons, but I'm unable to apply styles to those icons from within the component scss file, It works only from within the global scss file.

Since I deal with "svg", "polygon", "path" .... tags, it doesn't work in the component scss file.

Is there a way to make it work since I only use those svg's in my component ?

Code example :

<div id="sidenav-icon-section">
      <li class="bleu-icon">
          <a href="/">
                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve" data-inject-url="http://localhost:4200/assets/images/menu_items/accueil.svg" _ngcontent-c1="">
                <polygon fill="none" stroke="#000000" stroke-width="2" stroke-miterlimit="10" points="32,3 2,33 11,33 11,63 23,63 23,47 39,47   39,63 51,63 51,33 62,33 "></polygon>
                </svg>
            </a> 
        </li>
    </div>

This css code will work in my global scss file, but not in my component css file :

#sidenav-icon-section {

  .bleu-icon polygon {
    transition: .2s !important;
  }

  &:hover .bleu-icon polygon {
    stroke: #009999 !important;
  }
}

or even any css property like this :

svg {
dislay: none;
}
naspy971
  • 1,137
  • 2
  • 13
  • 31

2 Answers2

2

Please see this SO post: Angular 2 - innerHTML styling

which suggests prefacing the CSS selectors with

:host ::ng-deep.

i.e.

 :host ::ng-deep .bleu-icon polygon {
    transition: .2s !important;
  }

The linked SO post indicates that ::ng-deep is a bit of a hack (supporting mwilson's comment above) and that ::ng-deep is marked for depreciation. However, I haven't seen a proposed alternative, just lots of discussion that one is needed.

The other solution is to add the styles in javascript. I agree that this is just as awkward, because then why have SASS at all? But it works.

glenn
  • 271
  • 2
  • 6
1

Use encapsulation: ViewEncapsulation.None in your component decorator:

@Component({
  selector: '...',
  template: `...`,
  encapsulation: ViewEncapsulation.None
  ...
})

This will place your component's styling in your page's head tag.

benshabatnoam
  • 7,161
  • 1
  • 31
  • 52
  • 1
    This should come with a fine print text of "Will inadvertently apply styles to any matched selector within the application opposed to being encapsulated within the component". I think this is more of a hack. Kind of like using `::ng-deep` – mwilson Oct 16 '19 at 02:08