Angular:嵌入,设置SVG元素的颜色

Sno*_*lax 5 css sass angular

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

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

    </masterflex-logo>
</masterflex-sidebar>
Run Code Online (Sandbox Code Playgroud)

我的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() {
  }

}
Run Code Online (Sandbox Code Playgroud)

我的 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">
Run Code Online (Sandbox Code Playgroud)

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

Con*_*Fan 13

一个 SVG 元素有一个stroke和 一个fill颜色。您可以使用相应的元素或样式属性设置每一个:

<svg [attr.stroke]="color" ... >
<svg [style.stroke]="color" ... >
<svg [attr.fill]="color" ... >
<svg [style.fill]="color" ... >
Run Code Online (Sandbox Code Playgroud)

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

<my-svg-component [color]="myCustomColor" ...>
Run Code Online (Sandbox Code Playgroud)

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