简体   繁体   English

无法将样式应用到带有 Angular 的组件 css 中的 svg,只能在全局 css 文件中

[英]Unable to apply styles to svg's in component css with Angular, only in global css file

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.我有一个“Sidenav”组件,其中我使用 svg 作为菜单图标,但我无法从组件 scss 文件中将样式应用于这些图标,它只能在全局 scss 文件中工作。

Since I deal with "svg", "polygon", "path" .... tags, it doesn't work in the component scss file.由于我处理“svg”、“polygon”、“path”.... 标签,所以它在组件 scss 文件中不起作用。

Is there a way to make it work since I only use those svg's in my component ?有没有办法让它工作,因为我只在我的组件中使用那些 svg ?

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 :此 css 代码将适用于我的全局 scss 文件,但不适用于我的组件 css 文件:

#sidenav-icon-section {

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

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

or even any css property like this :甚至任何像这样的 css 属性:

svg {
dislay: none;
}

Please see this SO post: Angular 2 - innerHTML styling请参阅此 SO 帖子: Angular 2 - innerHTML 样式

which suggests prefacing the CSS selectors with这建议在 CSS 选择器前面加上

:host ::ng-deep.

ie IE

 :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.链接的 SO 帖子表明::ng-deep是一个黑客(支持上面的 mwilson 评论)并且::ng-deep标记为折旧。 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.另一种解决方案是在 javascript 中添加样式。 I agree that this is just as awkward, because then why have SASS at all?我同意这也很尴尬,因为那为什么要使用 SASS? But it works.但它有效。

Use encapsulation: ViewEncapsulation.None in your component decorator:在组件装饰器中使用encapsulation: ViewEncapsulation.None

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

This will place your component's styling in your page's head tag.这会将组件的样式放置在页面的head标记中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM