【问题标题】:Angular: transclusion, set color of SVG elementAngular:嵌入,设置SVG元素的颜色
【发布时间】:2018-07-26 15:10:17
【问题描述】:

我有一个 component.html 可以嵌入我的 svg 组件:

<masterflex-sidebar>
    <masterflex-logo sidebar-logo color="white">

    </masterflex-logo>
</masterflex-sidebar>

我的logo.ts 文件:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'masterflex-logo',
  templateUrl: './masterflex.component.html',
  styleUrls: ['./masterflex.component.scss']
})
export class MasterflexComponent implements OnInit {

  @Input() color:string

  constructor() { }

  ngOnInit() {
  }

}

我的 svg 组件(部分):

<svg 
    version="1.1" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    x="0px" y="0px"
    viewBox="0 0 237.4 35.9"
    height="35.9"
    width="237.4"
    xml:space="preserve" *ngIf="color">

我希望能够将我的 svg 组件的颜色更改为我想要的任何颜色(在我的第一个组件中使用 color="white" 设置)并将该颜色应用于我的 svg。有没有办法将该颜色属性传递给 scss 样式?

【问题讨论】:

  • “将颜色属性传递给 scss 样式”是什么意思?您可以使用属性绑定来设置 SVG 元素的颜色。这对你有用吗?
  • @ConnorsFan 那行得通,我只是在想怎么做,但还没弄明白

标签: css angular sass


【解决方案1】:

SVG 元素具有strokefill 颜色。您可以为每一个设置相应的元素或样式属性:

<svg [attr.stroke]="color" ... >
<svg [style.stroke]="color" ... >
<svg [attr.fill]="color" ... >
<svg [style.fill]="color" ... >

组件的color输入属性必须在父组件中设置:

<my-svg-component [color]="myCustomColor" ...>

您可以尝试this stackblitz中的代码。请注意,如果 SVG 元素内的形状和文本元素设置了自己的 strokefill 颜色,这些将覆盖在 SVG 元素级别设置的颜色。

【讨论】:

  • 完美,正是我所需要的。有没有一个地方我可以阅读元素中的 [] 东西​​是什么?我很难导航角度文档
  • 是的,您可以在文档的this page 中阅读有关 Angular 属性绑定的信息。实际上,关于模板语法的整页是必读的。
  • 当我使用 img 包裹在 svg 图像周围的标签时,是否可以更改填充颜色
  • @PardeepJain - 根据this answer,似乎只有内联 SVG 才有可能。尝试修改用作图像 src 的 SVG 元素的填充颜色时,我没有成功。
  • @ConnorsFan 是的,即使我已经尝试过,最终还是使用了 HTML 元素的背景掩码作为 SVG 图像并为其赋予了背景色。
【解决方案2】:

尝试这样做,

<svg 
    version="1.1" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    x="0px" y="0px"
    viewBox="0 0 237.4 35.9"
    height="35.9"
    width="237.4"
    xml:space="preserve" 
    style="color: {{color}}" *ngIf="color">

或者将它类似地应用于您在&lt;svg&gt;&lt;/svg&gt; 标签中的每个样式规则。不确定它是否是fill 而不是color,因为它是svg。看看有没有效果。

【讨论】:

  • 没用。该属性在标签上仅显示为样式,但没有颜色属性或其值。
猜你喜欢
  • 2012-07-16
  • 2018-02-09
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 2022-01-19
  • 2019-06-22
相关资源
最近更新 更多