【问题标题】:Unable to apply styles to svg's in component css with Angular, only in global css file无法使用 Angular 将样式应用于组件 css 中的 svg,仅在全局 css 文件中
【发布时间】:2019-06-07 17:27:04
【问题描述】:

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

由于我处理“svg”、“polygon”、“path”....标签,它在组件 scss 文件中不起作用。

有没有办法让它工作,因为我只在我的组件中使用那些 svg?

代码示例:

<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>

这个 css 代码可以在我的全局 scss 文件中工作,但不能在我的组件 css 文件中工作:

#sidenav-icon-section {

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

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

甚至任何像这样的css属性:

svg {
dislay: none;
}

【问题讨论】:

标签: css angular svg


【解决方案1】:

请参阅此 SO 帖子: Angular 2 - innerHTML styling

建议在 CSS 选择器前面加上

:host ::ng-deep.

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

链接的 SO 帖子表明 ::ng-deep 有点像 hack(支持上面 mwilson 的评论)并且 ::ng-deep 被标记为折旧。但是,我还没有看到建议的替代方案,只是需要进行大量讨论。

另一种解决方案是在 javascript 中添加样式。我同意这同样尴尬,因为那为什么还要有 SASS?但它有效。

【讨论】:

    【解决方案2】:

    在你的组件装饰器中使用encapsulation: ViewEncapsulation.None

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

    这会将组件的样式放置在页面的head 标记中。

    【讨论】:

    • 这应该带有“将不经意地将样式应用于应用程序中的任何匹配的选择器,而不是封装在组件中”的精美文本。我认为这更像是一种黑客行为。有点像使用::ng-deep
    猜你喜欢
    • 2020-12-25
    • 2021-01-15
    • 2017-03-17
    • 1970-01-01
    • 2018-12-18
    • 2018-12-13
    • 1970-01-01
    • 2023-03-08
    • 2019-04-18
    相关资源
    最近更新 更多